为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
,在不同的字段中将两者分开
将从root用户获取所有文档result:[]
要使用一个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" }
])