我有以下文件。
{
"_id": {
"$oid": "526fdc1fd6b0a8182300009c"
},
"body": "test abc",
"emb" : [{"body":"text","em":"abc.com","auth":"XYZ"},
{"body":"text","em":"abc.com","auth":"ABC"}
]
}
{
"_id": {
"$oid": "526fdc1fd6b0a8182300009d"
},
"body": "test abc",
"emb" : [{"body":"text","em":"abc.com","auth":"PQR"},
{"body":"text","em":"abc.com","auth":"ABC"}
]
}
如果我想计算内部文档数组中每个“auth”的出现次数,我该怎么做?我期待的结果是
"ABC":2
"PQR":1
"XYZ":1
答案 0 :(得分:1)
$unwind
emb
数组{$unwind: "$emb"}
emb.auth
{$group: { _id: "$emb.auth", count: { $sum:1 } } }
分组
醇>
这为您提供了所需的信息,但语法略有不同:
{ _id:"ABC", count:2 },
{ _id:"PQR", count:1 },
{ _id:"XYZ", count:1 }