您可以将要动态查询的数据存储为“类型化”键值对数组,如下所示:
query_data: [
{ type: "company", value: "foo" },
{ type: "plan", value: "pro" },
...
]
然后索引 .type 和 .value
鉴于您的示例,这将如下所示:
> db.xx.findOne()
{
"_id" : ObjectId("515ca2bc57a0887a97cc8d14"),
"name" : "Thiago",
"id" : 2093,
"country" : "Portugal",
"custom_data" : [
{
"type" : "company",
"value" : "foo"
},
{
"type" : "plan",
"value" : "pro"
},
{
"type" : "department",
"value" : "it"
},
{
"type" : "sessions",
"value" : 203
}
]
}
> db.xx.ensureIndex({country:1,"custom_data.type":1,"custom_data.value":1})
> db.xx.find({country:"Portugal","custom_data.type":"sessions","custom_data.value":{$gt:100}}).explain()
{
"cursor" : "BtreeCursor country_1_custom_data.type_1_custom_data.value_1",
"isMultiKey" : true,
"n" : 1,
"nscannedObjects" : 1,
"nscanned" : 1,
"nscannedObjectsAllPlans" : 1,
"nscannedAllPlans" : 1,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 0,
"indexBounds" : {
"country" : [
[
"Portugal",
"Portugal"
]
],
"custom_data.type" : [
[
"sessions",
"sessions"
]
],
"custom_data.value" : [
[
{
"$minElement" : 1
},
{
"$maxElement" : 1
}
]
]
},
"server" : "Aspire-5750:27017"
}