假设我有一个名为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命令的结果,该命令可以很好地挑选出唯一的值,但没有解释如何获得它们在集合中出现的次数之和。
发布于 2016-03-31 20:09:50
您应该使用聚合框架。
示例的解决方案:
db.collection.aggregate([{$group: {_id: "$name", count: {$sum: 1}}},
{$project: {name: "$_id", count: "$count", _id: 0}}]);https://stackoverflow.com/questions/36332929
复制相似问题