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

标签 mongodb mongodb-query aggregation-framework

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

我有以下 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 对嵌入的文档进行了分组。

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

具体例子

// 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

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"] }
              }
            }
          }
        }
      }
    }
  }}
])

关于mongodb - 没有 $unwind 的 $group 内部数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55726116/

相关文章:

mongodb - 使用官方 mongo-go-driver 进行正确的通配符多字段查询

node.js - 一次查询多个集合(mongodb)

node.js - mongoDB中如何统计总计数?

mongodb - 如何使用聚合来计算特定文档的总和?

mongodb - Mongo 聚合匹配多个值

mongodb - 将图像存储在 MongoDB 数据库中

javascript - mongodb native 驱动程序获取没有数据库名称的集合名称

node.js - Mongoose 在聚合中使用子查询来求和数据

node.js - MongoDB - 如何使用 Node.js 获取集合的大小?

java - Spring data mongodb搜索ISO日期