MongoDB 获取不同值的计数

标签 mongodb pymongo

假设我有一组记录:

{'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/

相关文章:

node.js - Mongoose 更新字段并添加新字段

超出 MongoDB 副本心跳请求时间

regex - 在 pymongo 中创建文本索引

python - 从 Python 快速查询大型 MongoDB 集合

python - pymongo 中的快速或批量更新

mongodb - 查询数据以在AWS中实现最小延迟的最佳方法

node.js - 如何解决未捕获的 ReferenceError : COLLECTION is not defined at <anonymous>:1:1 in Meteor. js/MongoDB

mongodb - MongoDB 服务因服务特定错误而终止无法创建另一个系统信号量

mongodb - 在 pyMongo 中查找文档的所有字段

python - Pymongo 的 update_one() 返回带有 AttributeError 的 UpdateResult