我想在 mongodb 中的另一个数组中聚合数据数组

I want to aggregate data array inside another array in mongodb

我想聚合 MongoDB 个在数组中包含数组的文档。我的文档如下所示。

{
  "_id": "6257e31d11a9d5231c05c084",
  "name": "Test Name 1",
  "phone": "1234567891",
  "visits": [
    {
      "_id": "6257e31d11a9d5231c05c069",
      "date": "2-7-2021",
      "samples": [
        "6257f8855197613b641d494e",
        ....
      ],
      "products_detailed": [
        "5d725cd2c4ded7bcb480eab2",
        .....

      ]
    },
    ...........
  ]
}

我想得到下面的输出行

{
  "_id": "6257e31d11a9d5231c05c084",
  "name": "Test Name 1",
  "phone": "1234567891",
  "visits": [
    {
      "_id": "6257e31d11a9d5231c05c069",
      "date": "2-7-2021",
      "samples": [
        {
          "_id": "6257f8855197613b641d494e",
          "product_name": "Samor",
          "price": 250
        },
        ........
      ],
      "products_detailed": [
        {
          "_id": "5d725cd2c4ded7bcb480eab2",
          "product_name": "Pahad",
          "price": 100
        },
        ............
      ]
    },
    .........................
  ]
}

我怎么会变成这样?我尝试使用 $lookup & group 来获取输出,但我没有得到我需要的输出。

因为您有每个文档的访问列表,所以一种方法是 $unwind,然后是最后的 $group,如下所示:

db.Main.aggregate([
  {
    $unwind: "$visits"
  },
  {
    "$lookup": {
      "from": "Samples",
      "localField": "visits.samples",
      "foreignField": "_id",
      "as": "samples"
    }
  },
  {
    "$lookup": {
      "from": "Product Detailed",
      "localField": "visits.products_detailed",
      "foreignField": "_id",
      "as": "products_detailed"
    }
  },
  {
    $project: {
      name: 1,
      phone: 1,
      "visits._id": 1,
      "visits.date": 1,
      "visits.products_detailed": "$products_detailed",
      "visits.samples": "$samples"
    }
  },
  {
    $group: {
      _id: 0,
      name: {$first: "$name"},
      visits: {$push: "$visits"}
    }
  }
])

正如您在 playground 中看到的那样,在您的数据样本中它将 return:

[
  {
    "_id": 0,
    "name": "Test Name 1",
    "visits": [
      {
        "_id": "6257e31d11a9d5231c05c069",
        "date": "2-7-2021",
        "products_detailed": [
          {
            "_id": "5d725cd2c4ded7bcb480eab2",
            "price": 100,
            "product_name": "Pahad"
          }
        ],
        "samples": [
          {
            "_id": "6257f8855197613b641d494e",
            "price": 250,
            "product_name": "Samor"
          }
        ]
      }
    ]
  }
]