问题描述
这是mongoDB中的文档结构
This is the document structure in mongoDB
{ "_id" :ObjectId("9elesdf3lk3jppefll34d210"), "category" :"data1",product:'data'}
{ "_id" :ObjectId("9elesdf3lk3jppefll34d211"), "category" : "data2",product:'data'}
{ "_id" :ObjectId("9elesdf3lk3jppefll34d211"), "category" : "data1",product:'data' }
其中索引了category
.我想对category
字段进行计数.
where category
is indexed. I want to take a distinct count of the category
field.
目前,我正在使用以下代码进行计数
Currently I am using the following code to take the counts
db.collection.aggregate(
{$group : {_id : "$category"} },
{$group: {_id:1, count: {$sum : 1 }}})
该查询为我提供了适当的计数,但是我的数据库每天都在增加,并且查询花费的时间更长.还有其他方法可以更快地进行计数吗?
This query was giving me proper counts but my database is increasing day by day and the query is taking longer to execute. Is there some other methodology to take the counts in a faster way?
推荐答案
如 JohnnyHK 所指出的,请使用 db.collection.distinct 可能,因为它提供了利用索引
As already pointed out by JohnnyHK, use db.collection.distinct if possible as it provides the chance of leveraging indexes
因此您的情况db.collection.distinct('category').length
应该非常快.
如果您仍然遇到性能问题,请查看
So in your case db.collection.distinct('category').length
should be pretty fast.
If you still suffer from performance issues then have a look at
db.collection.explain().distinct('category')
查看查询的执行计划并对其执行操作或将其提供给该问题,以便我们查看是否实际使用了您的索引.
to see the execution plan of the query and take actions on it or provide it to this question so that we see whether your index is actually used.
这篇关于计算mongoDB中的不同值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!