我想分别计算每个功能但我必须做错事。
添加$unwind
子句使查询不返回任何内容。
> db.animals.insert({name:"dog1", features:[{"desc": "large size"}, {"desc": "golden"}, {"desc": "hairy"}]})
WriteResult({ "nInserted" : 1 })
> db.animals.insert({name:"dog2", features:[{"desc": "large size"}, {"desc": "black"}, {"desc": "short legs"}]})
WriteResult({ "nInserted" : 1 })
> db.animals.aggregate([{ $group: { "_id": "$features.desc", "count": { $sum: 1} }}])
{ "_id" : [ "large size", "black", "short legs" ], "count" : 1 }
{ "_id" : [ "large size", "golden", "hairy" ], "count" : 1 }
> db.animals.aggregate([{$unwind: "$features.desc"}, { $group: { "_id": "$features.desc", "count": { $sum: 1} }}])
答案 0 :(得分:0)
我错误地添加了#34; .desc"在$ unwind子句中。删除它可以解决问题。
> db.animals.aggregate([{$unwind: "$features"}, { $group: { "_id": "$features.desc", "count": { $sum: 1} }}])
{ "_id" : "short legs", "count" : 1 }
{ "_id" : "large size", "count" : 2 }
{ "_id" : "golden", "count" : 1 }
{ "_id" : "black", "count" : 1 }
{ "_id" : "hairy", "count" : 1 }