Mongodb $in 或 $or 哪个更快?
Mongodb whats faster $in or $or?
哪个查询会更快?
ObjectId列表的Len可以大于2.
db.house.find(
{ persons:
{ $elemMatch:
{ person_id:
{ $in:
[ ObjectId("570028671d41c8eaeb6c9ce8"),
ObjectId("570028681d41c8eaeb6c9e38")
]
}
}
}
})
db.house.find(
{ $or:
[{ persons:
{$elemMatch:
{person_id:ObjectId("570028671d41c8eaeb6c9ce8")}}
},
{persons:{$elemMatch:
{person_id:ObjectId("570028681d41c8eaeb6c9e38")}}
}]
})
我有索引:人,persons.person_id。如果确实重要,我会从 Django (mongoengine) 进行查询。目前我的数据库中大约有 10 万间房屋和 2000 人。
房子文件是这样的:
{
"_id" : ObjectId("570031aa1d41c8ed54393b19"),
"persons" : [
{
"person_id" : ObjectId("570028671d41c8eaeb6c9dff"),
"t" : "150 t"
},
{
"person_id" : ObjectId("5700312d1d41c8ed54393b05"),
"t" : "1 g"
},
{
"person_id" : ObjectId("5700312d1d41c8ed54393b06"),
"t" : "70 y"
}
]
}
如 the documentation 中所述,应尽可能使用 $in
而不是 $or
。
但您也不需要使用 $elemMatch
,因为您直接匹配单个字段,因此您可以将查询简化为:
db.house.find(
{ 'persons.person_id':
{ $in:
[ ObjectId("570028671d41c8eaeb6c9ce8"),
ObjectId("570028681d41c8eaeb6c9e38")
]
}
})
哪个查询会更快? ObjectId列表的Len可以大于2.
db.house.find(
{ persons:
{ $elemMatch:
{ person_id:
{ $in:
[ ObjectId("570028671d41c8eaeb6c9ce8"),
ObjectId("570028681d41c8eaeb6c9e38")
]
}
}
}
})
db.house.find(
{ $or:
[{ persons:
{$elemMatch:
{person_id:ObjectId("570028671d41c8eaeb6c9ce8")}}
},
{persons:{$elemMatch:
{person_id:ObjectId("570028681d41c8eaeb6c9e38")}}
}]
})
我有索引:人,persons.person_id。如果确实重要,我会从 Django (mongoengine) 进行查询。目前我的数据库中大约有 10 万间房屋和 2000 人。 房子文件是这样的:
{
"_id" : ObjectId("570031aa1d41c8ed54393b19"),
"persons" : [
{
"person_id" : ObjectId("570028671d41c8eaeb6c9dff"),
"t" : "150 t"
},
{
"person_id" : ObjectId("5700312d1d41c8ed54393b05"),
"t" : "1 g"
},
{
"person_id" : ObjectId("5700312d1d41c8ed54393b06"),
"t" : "70 y"
}
]
}
如 the documentation 中所述,应尽可能使用 $in
而不是 $or
。
但您也不需要使用 $elemMatch
,因为您直接匹配单个字段,因此您可以将查询简化为:
db.house.find(
{ 'persons.person_id':
{ $in:
[ ObjectId("570028671d41c8eaeb6c9ce8"),
ObjectId("570028681d41c8eaeb6c9e38")
]
}
})