Search code examples
mongodbmongodb-queryaggregation-frameworkaggregate-functionsnosql-aggregation

Aggregation & $loockup


I am having two collections in MongoDB, I wanted to generate a report from it. The collection data as follows Students

[
    {
        _id:"1",
        name:"stu 1",
        class: "7th"
    },
    {
        _id:"2",
        name:"stu 2",
        class: "7th"
    },
    {
        _id:"3",
        name:"stu 1",
        class: "7th"
    }
]

Activities

[
    {
        _id:"1",
        studentIds:["1","3"],
        taskName:"Craft work 1"
    },
    {
        _id:"2",
        studentIds:["1"],
        taskName:"Craft work 2"
    }

]

The report I want to generate using aggregation pipeline as below, I am got struck with $loockup pipeline. Can someone help me with this?

Student Report

{
    _id:1
    name: "stu 1",
    class: "7th",
    tasks: ["Craft work 1", "Craft work 2"] 
},
{
    _id:1
    name: "stu 2",
    class: "7th",
    tasks: []   
},
{
    _id:1
    name: "stu 3",
    class: "7th",
    tasks: ["Craft work 1", "Craft work 2"] 
}

Solution

  • I'm assuming the studentIds field in activities is supposed to be an array. It appears to be a typo. If so you can aggregate the desired out put using:

    https://mongoplayground.net/p/UBE0oNWLBsR

    db.students.aggregate([
      {
        $lookup: {
          "from": "activities",
          "localField": "_id",
          "foreignField": "studentIds",
          "as": "tasks"
        }
      },
      {
        $addFields: {
          tasks: "$tasks.taskName"
        }
      }
    ])