Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I 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?

like image 471
Pat Avatar asked Mar 08 '12 17:03

Pat


People also ask

How do I search for an object in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object. Here is the query to search in an array of objects in MongoDB.

How do I query a nested object in MongoDB?

MongoDB Nested Query Match on a Nested Field You can use the dot notation (“field. nestedField”) to specify query criteria for fields in embedded/nested documents. For queries that use dot notation, fields and nested fields must be enclosed in double-quotes.

How do I access queries in MongoDB?

To query data from MongoDB collection, you need to use MongoDB's find() method.

When you query a collection MongoDB returns a object that contains the results of the query?

1. When you query a collection, MongoDB returns a ________ object that contains the results of the query. Explanation: The mongo shell then iterates over the cursor to display the results.


1 Answers

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.

db.Foo.aggregate(   {$unwind: "$bars"},   {$lookup: {     from:"bar",     localField: "bars",     foreignField: "_id",     as: "bar"     }},    {$match: {     "bar.testprop": true    }} ) 
like image 74
sidgate Avatar answered Oct 06 '22 23:10

sidgate