Mongodb组查询嵌入式文档

时间:2016-03-18 18:53:44

标签: mongodb mongodb-query pymongo

是否可以查询嵌入文档中特定键的值计数。

这是我的文件:

{ "_id" : 1, "drives" : [ {"fw": "A"}, {"fw": "B"} ] }
{ "_id" : 2, "drives" : [ {"fw": "B"}, {"fw": "C"} ] }
{ "_id" : 3, "drives" : [ {"fw": "A"}, {"fw": "C"} ] }
{ "_id" : 4, "drives" : [ {"fw": "A"}, {"fw": "D"} ] }

我想得到“fw”的计数:

输出:

计数:{“A”:3,“B”:2,“C”:2,“D”:1}

1 个答案:

答案 0 :(得分:3)

聚合会做到这一点。首先$unwind数组获取每fw个值的行,然后$group获取fw的值以及$sum的1来获取每个fw值;

db.test.aggregate( { $unwind: "$drives" }, 
                   { $group: { _id: "$drives.fw", cnt: {$sum:1} } } )

# { "_id" : "D", "cnt" : 1 }
# { "_id" : "C", "cnt" : 2 }
# { "_id" : "B", "cnt" : 2 }
# { "_id" : "A", "cnt" : 3 }