Javascript – How to query referenced objects in MongoDB


I've got two collections in my Mongo database, and the Foos contain references to one or more Bars:

Foo: { 
  prop1: true,
  prop2: true,
  bars: [
     "$ref": "Bar",
     "$id": ObjectId("blahblahblah")

Bar: {
   testprop: true

What I want is to find all of the Foos that have at least one Bar that has its testprop set to true. I've tried this command, but it doesn't return any results:

db.Foo.find({ "bars.testprop" : { "$in": [ true ] } })

Any ideas?

Best Solution

You can now do it in Mongo 3.2 using $lookup

$lookup takes four arguments

from: Specifies the collection in the same database to perform the join with. The from collection cannot be sharded.

localField: Specifies the field from the documents input to the $lookup stage. $lookup performs an equality match on the localField to the foreignField from the documents of the from collection.

foreignField: Specifies the field from the documents in the from collection.

as: Specifies the name of the new array field to add to the input documents. The new array field contains the matching documents from the from collection.

  {$unwind: "$bars"},
  {$lookup: {
    localField: "bars",
    foreignField: "_id",
    as: "bar"

   {$match: {
    "bar.testprop": true