0

How to lookup with object by reference id and other properties.

collectionA

{
  _id: ObjectId("6013859ba0c3120034d08bfa"),
  name: "A1",
  refs:[
   {id: ObjectId("6013859ba0c3120034d08bfb"), text: "ABC"},
   {id: ObjectId("6013859ba0c3120034d08bfc"), text: "DEF"}
  ]
}

collectionB

{
  _id: ObjectId("6013859ba0c3120034d08bfb"),
  name: "B1"
}

{
  _id: ObjectId("6013859ba0c3120034d08bfc"),
  name: "B2"
}

Expected Result

{
  _id: ObjectId("6013859ba0c3120034d08bfa"),
  name: 'A1',
  refs:[
   {id: ObjectId("6013859ba0c3120034d08bfb"), name: "B1", text: "ABC"},
   {id: ObjectId("6013859ba0c3120034d08bfc"), name: "B2", text: "DEF"}
  ]
}

1 Answer 1

2
  1. $unwind - Deconstruct refs array field.
  2. $lookup - Join collectionA (refs.id) with collectionB (_id).
  3. $project - Decorate the document, take first name from refsB array via $first.
  4. $group - Group by _id and generate (required) fields for the document(s).
db.collectionA.aggregate([
  {
    $unwind: "$refs"
  },
  {
    "$lookup": {
      "from": "collectionB",
      "localField": "refs.id",
      "foreignField": "_id",
      "as": "refsB"
    }
  },
  {
    $project: {
      _id: 1,
      name: 1,
      refs: {
        id: "$refs.id",
        text: "$refs.text",
        name: {
          $first: "$refsB.name"
        }
      }
    }
  },
  {
    $group: {
      _id: "$_id",
      name: {
        $first: "$name"
      },
      refs: {
        $push: "$refs"
      }
    }
  }
])

Sample Mongo Playground

Sign up to request clarification or add additional context in comments.

2 Comments

Oops, thanks a lot Takis_ for the point out. Missing out the parent's name. =)
it works. Thank you. I already added name like your update :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.