1

Facing a problem.

I have schema for tags and schema for course. Courses have an array of tags schema's ObjectIds.

How can I populate those tags with full schemas details.

Sample Tag Object
{
   _id: 44ffbvb...,
   title: "Tag 1
}

Sample Course Object

_id: 44ffaab23231,
tags: [ObjectId(44ffbvb...),..]

How can I populate those tags field performing $lookup stage in aggregation when using pipeline?

1 Answer 1

3

// Tag: collection name `tags`
[
  {
    _id: ObjectId("44ffbvb..."),
    title: "Tag 1"
  }
]

// Course: collection name `courses`
[
  {
    _id: ObjectId("44ffaab23231"),
    tags: [
      ObjectId("44ffbvb..."),
      ObjectId("44ffbvc..."),
      ObjectId("44ffbvd...")
    ]
  }
]

// Query using aggregate pipeline
db.courses.aggregate([
  {
    $match: {
      "name": "MongoDB"
    }
  },
  {
    $lookup: {
      from: "tags",
      let: { tags: "$tags" },
      pipeline: [
        {
          $match: {
            $expr: { $in: ["$_id", "$$tags"] }
          }
        },
        {
          $project: {
            "title": 1
          }
        }
      ],
      as: "tags"
    }
  }
])
Sign up to request clarification or add additional context in comments.

Comments

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.