Is it possible to $lookup without $unwind to use a property of current matched item?

Hello @Yilmaz_Durmaz,

Here don’t need lookup with the pipeline, you can pass an array of ids in localFields property,
Yes, You can use another approach without $unwind and $group stages,

  • $map to iterate loop of cart array
  • $filter to iterate loop of items array and find the specific _id’s item
  • $first to get the first element as an object from the above-filtered result, the alternate option is $arrayElemAt if you are using lower version of the MongoDB
  • $mergeObjects to merge the current cart object with the above-filtered item property, the alternate option is you can specify the properties name instead of using this operator
  • You can remove the items array by using $$REMOVE command because it’s not needed in the result, if you are using $project stage then don’t need this operation.
db.user.aggregate([
  {
    "$lookup": {
      "from": "items",
      "localField": "cart._id",
      "foreignField": "_id",
      "as": "items"
    }
  },
  {
    "$addFields": {
      "cart": {
        "$map": {
          "input": "$cart",
          "in": {
            "$mergeObjects": [
              "$$this",
              {
                "item": {
                  "$first": {
                    "$filter": {
                      "input": "$items",
                      "as": "i",
                      "cond": { "$eq": ["$$i._id", "$$this._id"] }
                    }
                  }
                }
              }
            ]
          }
        }
      },
      "items": "$$REMOVE"
    }
  }
])

Playground

4 Likes