Add Parent DBRef data in Child records as a Single object

This one should be simpler than the last one, you just need to have a lookup stage and then $unwind to convert the array to a single entry.

[
  {
    "_id": ObjectId("64a67f2fdbe7c36e2e6c15c6"),
    "address": "permenant address 1",
    "name": {
      "type": "permenant"
    },
    "parent": {
      "_id": ObjectId("64a67f32dbe7c36e2e6c15c8"),
      "data": {
        "age": "55"
      },
      "name": {
        "user": "xyz"
      }
    }
  },
  {
    "_id": ObjectId("64a67f2fdbe7c36e2e6c15c7"),
    "address": "permenant address 2",
    "name": {
      "type": "secondary"
    },
    "parent": {
      "_id": ObjectId("64a67f32dbe7c36e2e6c15c8"),
      "data": {
        "age": "55"
      },
      "name": {
        "user": "xyz"
      }
    }
  },
  {
    "_id": ObjectId("64a67f2fdbe7c36e2e6c15c3"),
    "address": "other address 2",
    "name": {
      "type": "other"
    },
    "parent": {
      "_id": ObjectId("64a67f32dbe7c36e2e6c15c8"),
      "data": {
        "age": "55"
      },
      "name": {
        "user": "xyz"
      }
    }
  }
]
db.Address.aggregate([
  {
    $lookup: {
      from: "Parent",
      localField: "parent.id",
      foreignField: "_id",
      as: "parent"
    }
  },
  {
    $unwind: "$parent"
  },
  
])

I’d recommend running through the Mongo University courses on these stages to get a good handle of them:

If from a relational background:

2 Likes