如何解决在汇总输出中添加单独的文档,以获取MongoDB中其他输出文档字段的总和
我目前有一个聚合查询,该查询分为三个阶段,可生成以下输出文档(其中只有两个):
{
"title" : "hr","num_files" : 420,"affected_files" : 0,"to_encrypt" : 6,"affected_file_percentage" : 0
}
{
"title" : "mktng","num_files" : 69,"affected_files" : 2,"to_encrypt" : 5,"affected_file_percentage" : 0.02898550724
}
我要添加具有以下输出的最后一个文档:
{
"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: []
将从根目录获取所有文档 -
total
创建一个单独的数组,其中包含一个对象,总数为$group
以求和字段
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" }
}
}
]
}
}
])
如果您只想将一个对象作为root的总数,请尝试
-
$facet
和$group
与上面的查询相同,之后添加了以下阶段 -
$project
使用$concatArrays
合并两个数组
-
$unwind
解构根数组 -
$replaceWith
替换root中的根对象
db.collection.aggregate([
{
$facet: {
result: [],affected_file_percentage: { $sum: "$affected_file_percentage" }
}
}
]
}
},{
$project: {
root: { $concatArrays: ["$result","$total"] }
}
},{ $unwind: "$root" },{ $replaceWith: "$root" }
])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。