听起来像这样可能是属性模式的一个很好的用途。详情见https://www.mongodb.com/blog/post/building-with-patterns-the-attribute-pattern...
顺便说一句,分成两个集合可能不会提供您所寻求的性能改进。
如果你有以下索引:
{
"is_happy": 1,
"like_baseball": 1,
"is_strong": 1,
}
并发出以下查询...
db.baseball.find({ is_happy: true, like_baseball: true, is_strong: false })
运行解释计划显示 Keys Examined 和 nReturned 之间的比率很好 (1:1)。
db.baseball.find({ is_happy: true, like_baseball: true, is_strong: false }).explain("allPlansExecution")
所有计划执行结果:
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "barrystuff.baseball",
"indexFilterSet" : false,
"parsedQuery" : {
"$and" : [
{
"is_happy" : {
"$eq" : true
}
},
{
"is_strong" : {
"$eq" : false
}
},
{
"like_baseball" : {
"$eq" : true
}
}
]
},
"winningPlan" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"is_happy" : 1,
"like_baseball" : 1,
"is_strong" : 1
},
"indexName" : "is_happy_1_like_baseball_1_is_strong_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"is_happy" : [ ],
"like_baseball" : [ ],
"is_strong" : [ ]
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"is_happy" : [
"[true, true]"
],
"like_baseball" : [
"[true, true]"
],
"is_strong" : [
"[false, false]"
]
}
}
},
"rejectedPlans" : [ ]
},
"executionStats" : {
"executionSuccess" : true,
"nReturned" : 3,
"executionTimeMillis" : 0,
"totalKeysExamined" : 3,
"totalDocsExamined" : 3,
"executionStages" : {
"stage" : "FETCH",
"nReturned" : 3,
"executionTimeMillisEstimate" : 0,
"works" : 4,
"advanced" : 3,
"needTime" : 0,
"needYield" : 0,
"saveState" : 0,
"restoreState" : 0,
"isEOF" : 1,
"invalidates" : 0,
"docsExamined" : 3,
"alreadyHasObj" : 0,
"inputStage" : {
"stage" : "IXSCAN",
"nReturned" : 3,
"executionTimeMillisEstimate" : 0,
"works" : 4,
"advanced" : 3,
"needTime" : 0,
"needYield" : 0,
"saveState" : 0,
"restoreState" : 0,
"isEOF" : 1,
"invalidates" : 0,
"keyPattern" : {
"is_happy" : 1,
"like_baseball" : 1,
"is_strong" : 1
},
"indexName" : "is_happy_1_like_baseball_1_is_strong_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"is_happy" : [ ],
"like_baseball" : [ ],
"is_strong" : [ ]
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"is_happy" : [
"[true, true]"
],
"like_baseball" : [
"[true, true]"
],
"is_strong" : [
"[false, false]"
]
},
"keysExamined" : 3,
"seeks" : 1,
"dupsTested" : 0,
"dupsDropped" : 0,
"seenInvalidated" : 0
}
},
"allPlansExecution" : [ ]
},
"serverInfo" : {
"host" : "Barry-MacBook-Pro.local",
"port" : 27017,
"version" : "4.0.6",
"gitVersion" : "caa42a1f75a56c7643d0b68d3880444375ec42e3"
},
"ok" : 1
}
虽然选择性可能不好,但这是数据的性质,查询仍然需要结果。如果您需要此查询并且希望获得更好的性能,您可能需要先考虑垂直缩放,然后如果仍然不能满足您的需求,请考虑水平缩放。
如果数据模型稳定且使用的字段名称一致,您或许可以根据需要使用覆盖查询。我怀疑您的实际需求并不像提供的示例那么微不足道。