假设我有一组记录:
{'name':'record1', 'colors':['red','green','blue']}
{'name':'record2', 'colors':['red','orange']}
{'name':'record3', 'colors':['red','yellow','blue']}
{'name':'record4', 'colors':['red','green','blue']}
我可以使用以下方法获取不同颜色的列表:
collection.distinct('colors')
#returns
['red','green','blue','orange','yellow']
是否有可能获得这些值出现的记录的数量?
例如:
[{'count':4,'color':'red'},{'count':2,'color':'green'}]
最佳答案
使用 $group 的聚合管道像这样的阶段:
db.collectionName.aggregate(
{ $unwind: "$colors" },
{ $group: { "_id": "$colors", "count": { $sum: 1 } } },
{ $project: { "color": "$_id", "count": 1 } }
);
因为您的文件将导致
{ "count" : 1, "color" : "yellow" }
{ "count" : 1, "color" : "orange" }
{ "count" : 3, "color" : "blue" }
{ "count" : 2, "color" : "green" }
{ "count" : 4, "color" : "red" }
不要忘记更改集合名称。
关于MongoDB 获取不同值的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39233075/