I've got two collections in my Mongo database, and the Foo
s contain references to one or more Bar
s:
Foo: { prop1: true, prop2: true, bars: [ { "$ref": "Bar", "$id": ObjectId("blahblahblah") } ] } Bar: { testprop: true }
What I want is to find all of the Foo
s 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?
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.
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.
To query data from MongoDB collection, you need to use MongoDB's find() method.
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.
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 }} )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With