简体   繁体   English

MongoDB:如何在对象数组中找到_id $?

[英]MongoDB: How to find _id $in array of objects?

I have a "group" collection which groups documents from another "item" collection. 我有一个“组”集合,该集合将另一个“项目”集合中的文档分组。 The group collection is simply an array of ObjectId's from the item collection, however I want to make the objects in the group array more complex and still be able to use the $in and $nin operators. group集合只是item集合中ObjectId的数组,但是我想使group数组中的对象更复杂,并且仍然能够使用$in$nin运算符。

How can I use $in when changing the value used with the $in operator to an object instead of only an ObjectId? $in运算符使用的值更改为对象而不是仅ObjectId时,如何使用$in

// current group document
{
  _id: ObjectId(...),
  items: [
    ObjectId(...),
    ObjectId(...)
  ]
}
// current item find query
db.item.find({ _id : { $in: group.items } }

I would like to change the group document to look like the following 我想将group文档更改为如下所示

{
  _id: ObjectId(...),
  items: [
     { _id : ObjectId(...), name: '...' },
     { _id : ObjectId(...), name: '...' }
  ]
}

Transform your group array to a simple array of ids to use for your find(): 将您的组数组转换为一个简单的ID数组,以用于find():

// revised item find logic
var itemGroupItemIds = group.items.map(function(item){
    return item._id
});
db.item.find({ _id : { $in: itemGroupItemIds } });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM