1

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

Community
  • 1
  • 1
Comfort Eagle
  • 2,112
  • 2
  • 22
  • 44

2 Answers2

3

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);
});
chridam
  • 100,957
  • 23
  • 236
  • 235
  • @harshavmb Correct – chridam Jun 13 '16 at 20:04
  • OP is using DBref which is not $lookup – VityaSchel Sep 03 '21 at 15:20
  • 1
    Thank you for demonstrating how to use $lookup in combination with DbRefs. In my opinion it illustrates that using the old DbRefs tends to make things more complicated. DbRefs should be avoided if possible. Also see https://www.compose.com/articles/mongodb-and-the-trouble-with-dbrefs/ – Stefan Nov 03 '21 at 17:04
  • A "manual reference" and combination of $lookup and $unwind might be what you are looking for. Also see https://stackoverflow.com/questions/41482559/how-to-return-single-object-instead-of-array-in-lookup-of-mongodb and https://feedback.mongodb.com/forums/924280-database/suggestions/44398599--populate-stage – Stefan Nov 04 '21 at 09:09
  • If there is an alternative to MongoDb that is able to handle document references in a better way, please let me know: https://softwarerecs.stackexchange.com/questions/81175/is-there-an-alternative-to-mongodb-that-allows-to-easily-resolve-document-refere – Stefan Nov 08 '21 at 08:15
1

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) {...});

Mongoose populate

irokhes
  • 1,643
  • 1
  • 14
  • 20