MongoDB计数不同速度

2024-06-01 01:57:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我在PyMongo中使用了以下代码:

db.collection.group(["myField"], {}, {"count":0},"function(o, p){p.count++}" )

它正确地返回了我需要的数字,但搜索需要30秒才能完成。索引会加快速度吗?我发现很难知道字段是否应该被索引,因为我读了一篇文章,上面说不要索引太多,否则一切都会变慢,所以我什么也没有索引。。在


Tags: 代码dbcount文章groupfunction数字collection
2条回答

计数现有密钥

参见:https://docs.mongodb.com/manual/reference/method/db.collection.count/

db.collection.count({"myField": {"$exists": True} })

按分组键计数

请参见:https://docs.mongodb.com/manual/reference/operator/aggregation/sum/#grp._S_sum

db.collection.aggregate([{"$group": {"_id": "myField", "count": {"$sum":1} }])

“group”很慢,因为它必须为遇到的每个文档执行一个Javascript函数。For this reason, the MongoDB manual says "group" is deprecated.“聚合”已经取代了“组”作为一种快速的现代方法来完成如下任务:

for result in c.aggregate([{
    "$group": {
        "_id": "$myField",
        "count": {"$sum": 1}
    }
}]):
    print("%s: %d" % (result["_id"], result["count"]))

See the MongoDB manual section about aggregation。在

相关问题 更多 >