MongoDB aggregation multiple operation

db.cItems.aggregate([
  {
    $match: {
      _id: {
        $eq: categoryId
      }
    }
  },
  {
    $lookup: {
      from: "items",
      localField: "itemId",
      foreignField: "_id",
      as: "parentItem"
    }
  },
  {
    "$unwind": "$items"
  },
  {
    $lookup: {
      from: "items",
      let: {
        itemId: "$items.itemId",
        items: "$items"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $eq: [
                "$_id",
                "$$itemId"
              ]
            }
          }
        },
        {
          $replaceRoot: {
            newRoot: {
              $mergeObjects: [
                "$$items",
                "$$ROOT"
              ]
            }
          }
        },
        {
          $project: {
            qty: 1,
            name: 1,
            description: 1
          }
        }
      ],
      as: "items"
    }
  },
  {
    $group: {
      _id: "$_id",
      items: {
        $push: {
          $first: "$items"
        }
      },
      name: {
        $first: {
          "$arrayElemAt": [
            "$parentItem.name",
            0
          ]
        }
      },
      description: {
        $first: {
          "$arrayElemAt": [
            "$parentItem.description",
            0
          ]
        }
      }
    }
  }
])
Topics: MongoDB

Related Code Examples