Mongodb格式的条件之间是否存在差异
{$and: [{a: 'aaa'}, {b: 'bbb'}]}
和没有$ and运算符的sam条件
{a: 'aaa', b: 'bbb'}
有人告诉我$ and运算符会使查询变慢。是真的吗谢谢。
答案 0 :(得分:1)
这些条件之间没有区别。回答此类问题的最佳方法是查看explain
的输出,以了解Mongo如何实际处理这样的查询。
如果您在下面的查询计划中查看winningPlan
,您会发现它们是完全一样的!
> db.my_test_coll.createIndex({a: 1, b: 1}); // adding an index
没有$and
:
> db.my_test_coll.find({a: 'aaa', b: 'bbb'}).explain()
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "test.my_test_coll",
"indexFilterSet" : false,
"parsedQuery" : {
"$and" : [
{
"a" : {
"$eq" : "aaa"
}
},
{
"b" : {
"$eq" : "bbb"
}
}
]
},
"winningPlan" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"a" : 1,
"b" : 1
},
"indexName" : "a_1_b_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"a" : [ ],
"b" : [ ]
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"a" : [
"[\"aaa\", \"aaa\"]"
],
"b" : [
"[\"bbb\", \"bbb\"]"
]
}
}
},
"rejectedPlans" : [ ]
},
"ok" : 1
}
使用$and
:
> db.my_test_coll.find({$and: [{a: 'aaa'}, {b: 'bbb'}]}).explain()
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "test.my_test_coll",
"indexFilterSet" : false,
"parsedQuery" : {
"$and" : [
{
"a" : {
"$eq" : "aaa"
}
},
{
"b" : {
"$eq" : "bbb"
}
}
]
},
"winningPlan" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"a" : 1,
"b" : 1
},
"indexName" : "a_1_b_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"a" : [ ],
"b" : [ ]
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"a" : [
"[\"aaa\", \"aaa\"]"
],
"b" : [
"[\"bbb\", \"bbb\"]"
]
}
}
},
"rejectedPlans" : [ ]
},
"ok" : 1
}