Search code examples
mongodbpopulate

How can I populate array of objectIds in mongodb aggregate?


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?


Solution

  • 
    // 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"
        }
      }
    ])