假设我有以下名为mydata
的集合:
{name: 'a', otherStuff: 'blah'},
{name: 'a', otherStuff: 'blah'},
{name: 'b', otherStuff: 'blah'},
{name: 'c', otherStuff: 'blah'},
{name: 'c', otherStuff: 'blah'},
{name: 'a', otherStuff: 'blah'}
如何获取唯一name
值的总和?
例如,我正在寻找:
{name: 'a', count: 3},
{name: 'b', count: 1},
{name: 'c', count: 2}
我已尝试过搜索,但我只看到引用distinct
命令的结果,该命令可以很好地挑出唯一值,但没有解释如何获得它们出现的次数的总和在集合中。
答案 0 :(得分:1)
您应该使用聚合框架。
您的示例解决方案:
db.collection.aggregate([{$group: {_id: "$name", count: {$sum: 1}}},
{$project: {name: "$_id", count: "$count", _id: 0}}]);