小编Som*_*lse的帖子

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

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

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

{
  arrayField: [ 
    { fieldA: value1, ...otherFields }, 
    { fieldA: value2, ...otherFields },
    { fieldA: value2, ...otherFields } 
  ],
  ...otherFields
}
Run Code Online (Sandbox Code Playgroud)

以下是我想要的。

{
  arrayField: [ 
    { fieldA: value1, ...otherFields }, 
    { fieldA: value2, ...otherFields },
    { fieldA: value2, ...otherFields } 
  ],
  newArrayField: [ 
    { fieldA: value1, count: 1 }, 
    { fieldA: value2, count: 2 },
  ],
  ...otherFields
}
Run Code Online (Sandbox Code Playgroud)

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

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

具体例子

// document structure
{
  _id: ObjectId(...),
  type: "test",
  results: [ 
    { choice: "a" …
Run Code Online (Sandbox Code Playgroud)

mongodb mongodb-query aggregation-framework

5
推荐指数
1
解决办法
1079
查看次数