Mongodb- 按键对数组进行分组

Mongodb- group an array by key

我在多个文档中有一个数组字段(包含对象),我想将这些数组合并为一个数组并按对象键对数组进行分组。我设法对数组进行了分组,但我不知道如何对数据进行分组。请参阅下面我尝试的代码

const test = await salesModel.aggregate([
            { $unwind: "$items" },
            {
                $group: {
                    _id: 0,
                    data: { $addToSet: '$items' }
                },
            }
        ])

查询结果:

{
  _id: 0,
  data: [
    {
      _id: 61435b3c0f773abaf77a367e,
      price: 3000,
      type: 'service',
      sellerId: 61307abca667678553be81cb,
    },
    {
      _id: 613115808330be818abaa613,
      price: 788,
      type: 'product',
      sellerId: 61307abca667678553be81cb,
    },
    {
      _id: 61307c1ea667676078be81cc,
      price: 1200,
      type: 'product',
      sellerId: 61307abca667678553be81cb,
    }
  ]
}

现在我想按对象键 data.sellerId 和总价

对数据数组进行分组

期望的输出:

{
  data: [
    {
      sumPrice: 788,
      sellerId: 613115808330be818abaa613,
    },
    {
      sumPrice: 1200,
      sellerId: 61307abca667678553be81cb,
    }
  ]
}

使用当前查询和结果扩展:

  1. $unwind:解构数组字段为多个文档
  2. $group:按 data.sellerId 分组以对 data.price.
  3. 求和 ($sum)
  4. $group: Group by 0 with $addToSet 将多个文档合并为一个文档 with data.

MongoDB aggregation query

db.collection.aggregate([
  {
    $unwind: "$data"
  },
  {
    $group: {
      _id: {
        sellerId: "$data.sellerId"
      },
      "sumPrice": {
        $sum: "$data.price"
      }
    }
  },
  {
    "$group": {
      "_id": 0,
      "data": {
        $addToSet: {
          "sellerId": "$_id.sellerId",
          "sumPrice": "$sumPrice"
        }
      }
    }
  }
])

Sample Mongo Playground

Output

[
  {
    "_id": 0,
    "data": [
      {
        "sellerId": ObjectId("61307abca667678553be81cb"),
        "sumPrice": 4988
      }
    ]
  }
]

如果您想重新编写查询,这里是带有示例输入的查询。

Input

[
  {
    items: [
      {
        _id: ObjectId("61435b3c0f773abaf77a367e"),
        price: 3000,
        type: "service",
        sellerId: ObjectId("61307abca667678553be81cb"),
        
      },
      {
        _id: ObjectId("613115808330be818abaa613"),
        price: 788,
        type: "product",
        sellerId: ObjectId("61307abca667678553be81cb"),
        
      },
      {
        _id: ObjectId("61307c1ea667676078be81cc"),
        price: 1200,
        type: "product",
        sellerId: ObjectId("61307abca667678553be81cb"),
        
      }
    ]
  }
]

Mongo aggregation query

db.collection.aggregate([
  {
    $unwind: "$items"
  },
  {
    $group: {
      _id: {
        sellerId: "$items.sellerId"
      },
      "sumPrice": {
        $sum: "$items.price"
      }
    }
  },
  {
    "$group": {
      "_id": 0,
      "data": {
        $addToSet: {
          "sellerId": "$_id.sellerId",
          "sumPrice": "$sumPrice"
        }
      }
    }
  }
])

Sample 2 on Mongo Playground

Output

[
  {
    "_id": 0,
    "data": [
      {
        "sellerId": ObjectId("61307abca667678553be81cb"),
        "sumPrice": 4988
      }
    ]
  }
]