在mongodb

时间:2016-04-16 22:29:10

标签: mongodb

我有以下文件。

{
    "_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

1 个答案:

答案 0 :(得分:1)

  1. $unwind emb数组{$unwind: "$emb"}
  2. 在使用emb.auth
  3. 计算时按{$group: { _id: "$emb.auth", count: { $sum:1 } } }分组

    这为您提供了所需的信息,但语法略有不同:

    { _id:"ABC", count:2 },
    { _id:"PQR", count:1 },
    { _id:"XYZ", count:1 }