首页 > 解决方案 > 按内部数组中的对象分组(mongodb 聚合)

问题描述

我有像这样的文档:

{
    "products": [
        {
           "uid": "aside-11kka-asdm12-asdjl"
           "price": 123,
           "count": 123
        }
    ]
}

我想将它分组到产品数组中,使用聚合(产品 uid 可以在另一个对象中重复)

标签: mongodbmongodb-queryaggregation-framework

解决方案


您需要$unwind首先对嵌套数组进行分组

db.collection.aggregate([
  {
    "$unwind": "$products"
  },
  {
    $group: {
      "_id": "$products.uid",
      "count": {
        $push: "$products.count"
      },
      "price": {
        $push: "$products.price"
      }
    }
  }
])

推荐阅读