Aggregation framework not working properly in mongodb

Viewed 32

I have HistorySchema collection and has doc as

{
    _id: ObjectId("60edb556ec3ad87aaa09bcc4"),
    billID: ObjectId("60edb556ec3ad87aaa09bcc3"),
    createdAt: "2021-07-13T15:46:30.569Z",
    updatedAt: "2021-07-13T15:46:30.569Z"
}

BillSchema collection as

{
   _id: ObjectId"60edb556ec3ad87aaa09bcc3",
   createdAt: "2021-07-13T15:46:30.485+00:00",
   updatedAt: "2021-07-13T15:46:30.485+00:00"
}

Now when I aggregate history with bill as

const history = await history.aggregate([
                {$lookup: {
                    from: "BillSchema",
                    localField: "billID",
                    foreignField: "_id",
                    as: "billData"
                }},
            ])

it returns history data but billData is always empty array as

[
   {
        "_id": "60edb556ec3ad87aaa09bcc4",
        "billID": "60edb556ec3ad87aaa09bcc3",
        "createdAt": "2021-07-13T15:46:30.569Z",
        "updatedAt": "2021-07-13T15:46:30.569Z",
        "__v": 0,
        "billData": []
    },
]
1 Answers

Your history collections's billId in string and bill collection billId is in integer. SO you need to convert

db.history.aggregate([
  {
    "$addFields": {
      "billID": {
        $toInt: "$billID"
      }
    }
  },
  {
    $lookup: {
      from: "bill",
      localField: "billID",
      foreignField: "_id",
      as: "billData"
    }
  }
])

Working Mongo playground

Related