首页 > 解决方案 > 如何对集合进行分组以汇总对象的属性并使用 MongoDB 生成计算字段

问题描述

如何按特定字段对集合进行分组并生成一个使用 mongoDB 对象的属性总和计算的字段,我不知道是否可以做我想做的事情,但我想知道。

我想按duelId字段分组以添加分数集合:

  {  "matches": [{
      "secondParticipant": {"name": "Maria","battlesWon": 2},
      "firstParticipant": {"name": "Fabio","battlesWon": 1},
      "duelId": "6c3e532d-3c0e-4438-8289-c86a4a51a102",
    },{
      "secondParticipant": {"name": "Fabio","battlesWon": 1 },
      "firstParticipant": {"name": "Maria","battlesWon": 1 },
      "duelId": "6c3e532d-3c0e-4438-8289-c86a4a51a102"
    },
    {
      "secondParticipant": {"name": "Luiz","battlesWon": 1},
      "firstParticipant": {"name": "Jose","battlesWon": 1},
      "duelId": "6c3e532d-3c0e-4438-8289-c86a4a51a666"
    }]}

预期的:

 {[ [
      {
        "secondParticipant": {"name": "Maria","battlesWon": 2 },
        "firstParticipant": {"name": "Fabio","battlesWon": 1 },
        "duelId": "6c3e532d-3c0e-4438-8289-c86a4a51a102",
      },{
        "secondParticipant": {"name": "Fabio","battlesWon": 1},
        "firstParticipant": {"name": "Maria","battlesWon": 1},
        "duelId": "6c3e532d-3c0e-4438-8289-c86a4a51a102"
      },
      "score": { "Fabio": 2, "Maria": 3 } *// this field would be the sum of battlesWon after grouping*
    ], 
    [
      {
        "secondParticipant": {"name": "Luiz","battlesWon": 1},
        "firstParticipant": {"name": "Jose","battlesWon": 1},
        "duelId": "6c3e532d-3c0e-4438-8289-c86a4a51a666"
      },
      "score": { "Luiz": 1, "Jose": 1 } // *this field would be the sum of battlesWon after grouping*
    ]]}

标签: mongodbmongoosemongodb-query

解决方案


您可以执行以下操作:

  1. $unwindmatches数组_
  2. 重命名firstParticipantsecondParticipant放入 kv 元组数组以进行进一步处理
  3. 按决斗和名称分组,总结每个参与者的分数
  4. 按决斗分组以获取每个决斗请求的名称分数元组
  5. 用于$arrayToObject将步骤 2 中的 kv 元组数组转换回请求的形式。

这是Mongo Playground供您参考。


推荐阅读