Reputation: 2462
I'm new to mongodb, so sorry if this questions is dumb: I've pulled a document with the following structure:
{
"_id" : ObjectId("575df70512a1aa0adbc2b496"),
"name" : "something",
"content" : {
"product" : {
"$ref" : "products",
"$id" : ObjectId("575ded1012a1aa0adbc2b394"),
"$db" : "mdb"
},
"client" : {
"$ref" : "clients",
"$id" : ObjectId("575ded1012a1aa0adbc2b567"),
"$db" : "mdb"
}
}
where I'm referring to documents in the products
and clients
collection. I've read that it is possible to resolve these DBRefs on client-side (https://stackoverflow.com/a/4067227/1114975).
How do I do this? I'd like to avoid querying these objects and embedding them into the document. Thank you
Upvotes: 1
Views: 1668
Reputation: 1703
I would consider use Mongoose which helps you with this and other issues. In this case you can use something like:
Collection.find({}).populate('products').populate('clients')
.exec(function(err, books) {...});
Upvotes: 1
Reputation: 103365
You can resolve this with the $lookup
operator. Consider the following aggregation pipeline:
// Execute aggregate, notice the pipeline is expressed as an Array
collection.aggregate([
{
"$lookup": {
"from": "product",
"localField": "content.product.$id",
"foreignField": "_id",
"as": "products"
}
},
{
"$lookup": {
"from": "clients",
"localField": "content.client.$id",
"foreignField": "_id",
"as": "clients"
}
},
], function(err, result) {
console.log(result);
});
Upvotes: 3