Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为MongoDB中其他输出文档字段的总和在聚合输出中添加单独的文档_Mongodb_Aggregation Framework - Fatal编程技术网

为MongoDB中其他输出文档字段的总和在聚合输出中添加单独的文档

为MongoDB中其他输出文档字段的总和在聚合输出中添加单独的文档,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我目前有一个包含三个阶段的聚合查询,它生成以下输出文档(这只是其中的两个): 我想添加具有以下输出的最后一个文档: { "title" : "total", "num_files" : [sum of all files], "affected_files" : [sum of all affected files], "to_encrypt&

我目前有一个包含三个阶段的聚合查询,它生成以下输出文档(这只是其中的两个):

我想添加具有以下输出的最后一个文档:

{
        "title" : "total",
        "num_files" : [sum of all files],
        "affected_files" : [sum of all affected files],
        "to_encrypt" : [sum of all files to be encrypted],
        "affected_file_percentage" : [total percentage]
}

我在聚合函数中找不到任何内容,因为在管道中添加另一个阶段来对所有内容进行求和将不允许我显示单个文档。我想在输出中显示这些和总计。如何做到这一点?

您可以使用
$facet
,在不同的字段中将两者分开

  • result:[]
    将从root用户获取所有文档
  • total
    要使用一个total对象创建单独的数组,
    $group
    要对数字字段求和


如果您只需要根目录中的total对象,请尝试

  • $facet
    $group
    与上述查询相同,之后添加以下阶段
  • $project
    使用
    $concatarray
  • $unwind
    解构根数组
  • $replaceWith
    替换根目录中的根对象

{
        "title" : "total",
        "num_files" : [sum of all files],
        "affected_files" : [sum of all affected files],
        "to_encrypt" : [sum of all files to be encrypted],
        "affected_file_percentage" : [total percentage]
}
db.collection.aggregate([
  {
    $facet: {
      result: [],
      total: [
        {
          $group: {
            _id: null,
            title: { $first: "total" },
            num_files: { $sum: "$num_files" },
            affected_files: { $sum: "$affected_files" },
            to_encrypt: { $sum: "$to_encrypt" },
            affected_file_percentage: { $sum: "$affected_file_percentage" }
          }
        }
      ]
    }
  }
])
db.collection.aggregate([
  {
    $facet: {
      result: [],
      total: [
        {
          $group: {
            _id: null,
            title: { $first: "total" },
            num_files: { $sum: "$num_files" },
            affected_files: { $sum: "$affected_files" },
            to_encrypt: { $sum: "$to_encrypt" },
            affected_file_percentage: { $sum: "$affected_file_percentage" }
          }
        }
      ]
    }
  },
  {
    $project: {
      root: { $concatArrays: ["$result", "$total"] }
    }
  },
  { $unwind: "$root" },
  { $replaceWith: "$root" }
])