Search code examples
mongodbazure-cosmosdbazure-cosmosdb-mongoapi

MongoDB: return field in child documents that is only present in the parent?


I have this Mongo DB Query that is returning in format I expect:

db.getCollection("myCollection").aggregate([
  {
    $lookup: {
      from: "myCollection",
      localField: "parent_id",
      foreignField: "parent_id",
      as: "children"
    }
  },
  { $unwind: "$children" },
  { $replaceWith: "$children" }
])

However, I also want the parent_desc field that is only present in the parent docs to be returned in the child docs in my response

example child doc:

{
id: doc_123_2
parent_id: 123
active: true
}

example parent doc:

{
_id: doc_123
parent_id: 123
active: true
parent_desc: sample parent desc
}

How can I modify my query to do so?


Solution

  • MongoDB: return field in child documents that is only present in the parent?

    To return the field present in parent to child document you can follow the below code. It uses addFields to add the required field parent_desc into the child document as shown in the output below:

    db.getCollection("newcoll").aggregate([
      {
        $lookup: {
          from: "newcoll",
          localField: "parent_id",
          foreignField: "parent_id",
          as: "children"
        }
      },
      { $unwind: "$children" },
      { $replaceWith: "$children" },
      {
        $lookup: {
          from: "newcoll",
          localField: "parent_id",
          foreignField: "parent_id",
          as: "parent"
        }
      },
      { $unwind: "$parent" },
      {
        $addFields: {
          parent_desc: "$parent.parent_desc"
        }
      },
      {
        $group: {
          _id: "$_id",
          id: { $first: "$id" },
          parent_id: { $first: "$parent_id" },
          active: { $first: "$active" },
          parent_desc: { $first: "$parent_desc" }
        }
      },
      {
        $project: {
          _id: 1,
          id: 1,
          parent_id: 1,
          active: 1,
          parent_desc: 1
        }
      }
    ]).pretty()
    

    Output:

    {
            "_id" : ObjectId("662616f0af88e119ac2f49c3"),
            "id" : "doc_123_2",
            "parent_id" : "123",
            "active" : true,
            "parent_desc" : "sample parent desc"
    }
    {
            "_id" : ObjectId("66261744af88e119ac2f49c4"),
            "id" : "doc_123",
            "parent_id" : "123",
            "active" : true,
            "parent_desc" : "sample parent desc"
    }