没有 $unwind 的 $group 内部数组值

2023-12-24

我想按指定字段的相同值对数组中的对象进行分组并生成计数。

我有以下 mongodb 文档(不存在不相关字段)。

{
  arrayField: [ 
    { fieldA: value1, ...otherFields }, 
    { fieldA: value2, ...otherFields },
    { fieldA: value2, ...otherFields } 
  ],
  ...otherFields
}

以下是我想要的。

{
  arrayField: [ 
    { fieldA: value1, ...otherFields }, 
    { fieldA: value2, ...otherFields },
    { fieldA: value2, ...otherFields } 
  ],
  newArrayField: [ 
    { fieldA: value1, count: 1 }, 
    { fieldA: value2, count: 2 },
  ],
  ...otherFields
}

这里我按 fieldA 对嵌入文档进行分组。

我知道如何通过以下方式进行放松和两个小组赛。 (无关阶段省略)

具体例子

// document structure
{
  _id: ObjectId(...),
  type: "test",
  results: [ 
    { choice: "a" }, 
    { choice: "b" },
    { choice: "a" } 
  ]
}
db.test.aggregate([
{ $match: {} },
{
  $unwind: {
    path: "$results",
    preserveNullAndEmptyArrays: true
  }
},
{
  $group: {
    _id: {
      _id: "$_id",
      type: "$type",
      choice: "$results.choice",
    },
    count: { $sum: 1 }
  }
},
{
  $group: {
    _id: {
      _id: "$_id._id",
      type: "$_id.type",
      result: "$results.choice",
    },
    groupedResults: { $push: { count: "$count", choice: "$_id.choice" } }
  }
}
])

您可以使用下面aggregation https://mongoplayground.net/p/tVe3_ScYClb

db.test.aggregate([
  { "$addFields": {
    "newArrayField": {
      "$map": {
        "input": { "$setUnion": ["$arrayField.fieldA"] },
        "as": "m",
        "in": {
          "fieldA": "$$m",
          "count": {
            "$size": {
              "$filter": {
                "input": "$arrayField",
                "as": "d",
                "cond": { "$eq": ["$$d.fieldA", "$$m"] }
              }
            }
          }
        }
      }
    }
  }}
])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

没有 $unwind 的 $group 内部数组值 的相关文章

随机推荐