如何获取文档MangoDB&Mongoose的特定字段并聚合部分字段?

How to get specific fields on document MangoDB&Mongoose and aggregate some of the fields?

我的数据是这样的:

[
   {
      "_id":"61717cafd351f3ae8b6d205a",
      "restaurant":"Hogwarts",
      "purchasedAt":"2021-10-20T17:47:40.166Z",
      "products":[
         {
            "name":"Meat Samosa",
            "price":3.95,
            "quantity":1,
            "_id":"61717cafd351f3ae8b6d205b"
         },
         {
            "name":"Pilau Rice",
            "price":2.95,
            "quantity":1,
            "_id":"61717cafd351f3ae8b6d205f"
         }
      ]
   },
   {
      "_id":"61717cb2d351f3ae8b6dd05b",
      "restaurant":"Hogwarts",
      "purchasedAt":"2021-10-20T03:14:11.111Z",
      "products":[
         {
            "name":"Pilau Rice",
            "price":2.95,
            "quantity":1,
            "_id":"61717cb2d351f3ae8b6dd05d"
         }
      ]
   },
]

我正在尝试查找一个查询,该查询可以获取所有产品(无重复)及其数量的总和。请注意,即使产品相同(名称相同),产品 ID 也不同。理想情况下,我的回复应该是这样的

[
  { 
    name: "Meat Samosa",
    price: 3.95,
    quantity: 1
 },
 {
   name: "Pilau Rice",
   price: 2.95,
   quantity: 2
 }
] 
  • $project 显示必填字段
  • $unwind解构products数组
  • $group by name 得到第一个 price 并计算 quantity 总和
  • $project 显示必填字段
db.collection.aggregate([
  {
    $project: {
      _id: 0,
      products: 1
    }
  },
  { $unwind: "$products" },
  {
    $group: {
      _id: "$products.name",
      price: { $first: "$products.price" },
      quantity: { $sum: "$products.quantity" }
    }
  },
  {
    $project: {
      _id: 0,
      name: "$_id",
      price: 1,
      quantity: 1
    }
  }
])

Playground