Database MongoDB:$lookup在索引属性上,而$in在非索引属性上
我目前正在使用MongoDB 3.5,我有两个集合用户,items。每个用户都有一个项目列表Database MongoDB:$lookup在索引属性上,而$in在非索引属性上,database,mongodb,performance,aggregation-framework,Database,Mongodb,Performance,Aggregation Framework,我目前正在使用MongoDB 3.5,我有两个集合用户,items。每个用户都有一个项目列表 //users { _id: ObjectId('userObjId1') itemArray: [ { ObjectId('itemA'), specialId: '123-this-is-unique'}, { ObjectId('itemB'), specialId: '456-this-is-unique'}, { ObjectId('itemC
//users
{
_id: ObjectId('userObjId1')
itemArray: [
{ ObjectId('itemA'), specialId: '123-this-is-unique'},
{ ObjectId('itemB'), specialId: '456-this-is-unique'},
{ ObjectId('itemC'),specialId: '789-this-is-unique'},
]
}
及项目
//items
{
_id: ObjectId('itemA')
specialId: '123this-is-unique'
owner: ObjectId('userObjId1')
}
我的一个操作涉及查询用户,给定一个特殊数组
在“我的项目”集合中,项目的SpecialId被编入索引
哪一个是更好的实践和潜在更好的性能
使用$in运算符查询用户集合中的SpecialId数组。
优点:查询位于同一集合中
缺点:每个用户中的itemArray本身没有索引,据我所知,这可能会影响性能
B在items集合中查询,投影所有者并使用它在users集合中运行$lookup
优点:较新的sytanx,因为SpecialId已经在items集合中建立了索引,所以它的性能应该更好。
缺点:需要在一个查询中访问两个集合这取决于您有多少用户,以及每个用户有多少项 如果您有少量用户,几十个或数百个,或者您可以在{itemArray.specialId:1}上创建索引,那么计划A将很好地工作
计划B将使用specialId上的索引来选择项目,然后在查找过程中使用users集合中的_id索引,这应该会执行得相当好。谢谢您的回答!实际上,我会有很多用户,但itemsArray的用户可能会少一些。那样的话,我想我应该采用B计划。