1

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.

How can I use $in when changing the value used with the $in operator to an object instead of only an ObjectId?

// 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

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

1 Answer 1

3

Transform your group array to a simple array of ids to use for your find():

// revised item find logic
var itemGroupItemIds = group.items.map(function(item){
    return item._id
});
db.item.find({ _id : { $in: itemGroupItemIds } });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.