我有资产收集,其中包含数据
{
"_id" : ObjectId("5bfb962ee2a301554915"),
"users" : [
"abc.abc@abc.com",
"abc.xyz@xyz.com"
],
"remote" : {
"source" : "dropbox",
"bytes" : 1234
}
{
"_id" : ObjectId("5bfb962ee2a301554915"),
"users" : [
"pqr.pqr@pqr.com",
],
"remote" : {
"source" : "google_drive",
"bytes" : 785
}
{
"_id" : ObjectId("5bfb962ee2a301554915"),
"users" : [
"abc.abc@abc.com",
"abc.xyz@xyz.com"
],
"remote" : {
"source" : "gmail",
"bytes" : 5647
}
我正在寻找的是用户分组,并根据其来源获得字节总数
{
"_id" : "abc.abc@abc.com",
"bytes" : {
"google_drive": 1458,
"dropbox" : 1254
}
}
我没有得到如何使用分组获得嵌套输出 . 我尝试过查询
db.asset.aggregate(
[
{$unwind : '$users'},
{$group:{
_id:
{'username': "$users",
'source': "$remote.source",
'total': {$sum: "$remote.bytes"}} }
}
]
)
这样我就可以用重复的用户名获得结果 .
2 回答
使用MongoDb 3.6及更高版本,您可以在 $mergeObjects 表达式和 $replaceRoot 管道中使用 $arrayToObject 运算符来获得所需的结果 .
您需要运行以下聚合管道:
产量
使用上面的示例文档 .
你必须在这里使用$group几次 . 首先使用
users
和source
并使用$sum计算总字节数 .第二个是
users
和$pushsource
和bytes
成一个数组即使您想将
source
和bytes
转换为键值格式,然后使用以下两个阶段替换最后的$group
阶段 .