通过聚合和 $facet 在 MongoDB 中为每个文档添加一个新字段。

3

我的示例数据类似于以下内容:

Category      response
Privacy         1
Mobile          1
Privacy         1
Privacy         2

我想要添加一个新字段Total,该字段的值为所有response字段值的总和。所需输出如下:
Category      response   Total
Privacy         1         5
Mobile          1         5
Privacy         1         5
Privacy         2         5

我该如何在MongoDB中获取这个输出结果。
1个回答

2

更新:由于Total的值不是固定的,因此更新了问题的答案:

/** Using 'facet' as we need docs to be returned in result 
  * (Can also be done without 'facet' by pushing all docs into an array in '$group' but it may not work for large datasets) */
db.collection.aggregate([
  {
    $facet: {
      data: [ { $match: {} } ], /** Get all docs without any filter */
      total: [
        {
          $group: { /** Group all docs & sum-up 'result' field */
            _id: "",
            Total: { $sum: "$response" }
          }
        }
      ]
    }
  },
  {
    $unwind: "$data"
  },
  {
    $unwind: "$total"
  },
  /** Merge 'total' field into 'data' & make data field as new root for documents */
  {
    $replaceRoot: { newRoot: { $mergeObjects: [ "$total", "$data" ] } }
  }
])

测试 : MongoDB游乐场

原文 : 如果所有文档的 Total 值相同。

如果聚合结果中需要在所有文档中添加相同的值,则只需使用聚合阶段 $addFields

{ $addFields : { Total :5 } }

它不是固定的5,随着新文档的插入而改变。 - Kamlesh Kanazariya
@KamleshKanazariya:我刚意识到你不需要做$unwind : total而是在$mergeObjects中用{$arrayElemAt :['$total',0]}替换$total!! - whoami - fakeFaceTrueSoul

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接