Search code examples
mongodbmongodb-queryaggregation-frameworkone-to-manymongodb-lookup

One to Many MongoDB lookup with project req fields


I have a one to many relationship of two Collections say A to B. How can I i show the desired output in one document for each id. For example, I have

/*Collection A*/
{
    "a_Id": "abc",
        "name": "xyz",
        "age": 5
}       

...//Other docs

/*Collection B*/
{
    "b_id": "abc",
    "FeeAmount": 800000,
    "invoiceNumber": "A10",
    "Date": "2021-10-29T00:00:00.000+04:00",
    "PaidAmount": 200000
},
{
    "b_id": "abc",
    "FeeAmount": 90,
    "invoiceNumber": "A20",
    "Date": "2021-10-29T00:00:00.000+04:00",
    "PaidAmount": 20
}

//...other docs multiple for different ids eg abc1,abc2

How can I achieve the following output after lookup on base of id? This is one document per id.

    /*Desired OutPut*/
//Document 1
    {
       "name": "xyz",
        "age": 5
       "availableLimitAmount": 800000,
      "FeeAmount": 800000,
        "invoiceNumber": "A10",
        "Date": "2021-10-29T00:00:00.000+04:00",
        "PaidAmount": 200000
    },
    {
        "name": "xyz",
         "age": 5
        "FeeAmount": 90,
        "invoiceNumber": "A20",
        "Date": "2021-10-29T00:00:00.000+04:00",
        "PaidAmount": 20
    }
//Document 2
 {
       "name": "qwe",
        "age": 50
       "availableLimitAmount": 20000,
      "FeeAmount": 40000,
        "invoiceNumber": "B10",
        "Date": "2021-1-1T00:00:00.000+04:00",
        "PaidAmount": 1000
    },
    {
        "name": "qwe",
         "age": 50
        "FeeAmount": 40,
        "invoiceNumber": "B20",
        "Date": "2021-2-2T00:00:00.000+04:00",
        "PaidAmount": 500
    }

Solution

  • Here is a working solution for how you can achieve that.

    db.coll1.aggregate([
      {
        $lookup: {
          localField: "a_Id",
          from: "coll2",
          foreignField: "b_id",
          as: "data",
          
        }
      },
      {
        $unwind: "$data"
      },
      {
        $replaceRoot: {
          "newRoot": {
            "$mergeObjects": [
              "$$ROOT",
              "$data"
            ]
          }
        }
      },
      {
        $project: {
          "data": 0
        }
      }
    ])
    

    Updated

    db.coll1.aggregate([
      {
        $lookup: {
          localField: "a_Id",
          from: "coll2",
          foreignField: "b_id",
          as: "data",
          
        }
      },
      {
        $unwind: "$data"
      },
      {
        $replaceRoot: {
          "newRoot": {
            "$mergeObjects": [
              "$$ROOT",
              "$data"
            ]
          }
        }
      },
      {
        $project: {
          "data": 0
        }
      },
      {
        $group: {
          _id: "$a_Id",
          data: {
            $push: "$$ROOT"
          }
        }
      }
    ])