I have two mongo collections:
defn
"_id" : ObjectId("8570bebcb7db3"),
"fields" : [ {
"control" : { "appearance" : "field-list" },
"children" : [ { "bind" : { "required" : "yes" }, ...
data
"_id" : ObjectId("1570bf18a7db"),
"defn" : ObjectId("8570bebcb7db3"),
"data" : {
"country" : "",
"age" : 1,
"age_unit" : "years",
},
"label" : "type"
that are joined where defn._id =data.defn
How can I write a query to return data.label for defn._id? The query would be of the form db.defn.find({ data.label where defn._id= "X"})
If you're using MongoDB 3.2, the $lookup stage can perform the equivalent of a left outer join.
The documentation provides an example of using this operation here.
Example using your data:
db.defn.insert({
"_id" : "123456",
"some_text" : "main document"
})
db.data.insert( {
"defn" : "123456",
"label" : "data we want to access"
})
db.defn.aggregate( [
{ "$lookup" : {
"from" : "data",
"localField" : "_id",
"foreignField" : "defn",
"as" : "defns"
}
}
])
// Results:
// {
// "_id" : "123456",
// "some_text" : "main document",
// "defns" : [ {
// "_id" : ObjectId("57a2cbbbeb99ff285a1f0893"),
// "defn" : "123456",
// "label" : "data we want to access"
// } ]
// }
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