capnbishop
capnbishop

Reputation: 83

Mongo, match documents who's _id is in an array as part of a subdocument

Using MongoDB, I want to find all documents in one collection who's _id shows up in an array of sub-documents in another collection. Using the $in operator doesn't really work here, because I'm only trying to match against a single value in the sub-document.

Suppose I have the following document from db.foos:

{ _id: 1, foo: [ { bar_id: 1 }, { bar_id: 3 } ] }

and the following collection of db.bars:

{ _id: 1, foo: "bar" }
{ _id: 2, foo: "abr" }
{ _id: 3, foo: "rab" }

I want to find all documents in db.bars who's _id can be found in the foo array (returning db.bars with _id 1 and 3, in this case). Something like this:

var foos = db.foos.findOne( { _id: 1 } )
db.bars.find( _id: { $in: foos.foo.bar_id } )

Of course, that won't work. How would I go about accomplishing this?

Upvotes: 2

Views: 46

Answers (1)

Sede
Sede

Reputation: 61225

You can use the collection.distinct method to get distinct _id values from the foo

db.bars.find({ '_id': { '$in': db.foos.distinct('foo.bar_id', {'_id': 1}) }})

Demo:

> db.foos.distinct('foo.bar_id', {'_id': 1})
[ 1, 3 ]
> db.bars.find({ '_id': { '$in': db.foos.distinct('foo.bar_id', {'_id': 1})}})
{ "_id" : 1, "foo" : "bar" }
{ "_id" : 3, "foo" : "rab" }

Upvotes: 1

Related Questions