Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I run this command:

db.ads_view.aggregate({$group: {_id : "$campaign", "action" : {$sum: 1} }});

ads_view : 500 000 documents.

this queries take 1.8s . this is its profile : https://gist.github.com/afecec63a994f8f7fd8a

indexed : db.ads_view.ensureIndex({campaign: 1});

But mongodb don't use index. Anyone know if can aggregate framework use indexes, how to index this query.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

This is a late answer, but since $group in Mongo as of version 4.0 still won't make use of indexes, it may be helpful for others.

To speed up your aggregation significantly, performe a $sort before $group.

So your query would become:

db.ads_view.aggregate({$sort:{"campaign":1}},{$group: {_id : "$campaign", "action" : {$sum: 1} }});

This assumes an index on campaign, which should have been created according to your question. In Mongo 4.0, create the index with db.ads_view.createIndex({campaign:1}).

I tested this on a collection containing 5.5+ Mio. documents. Without $sort, the aggregation would not have finished even after several hours; with $sort preceeding $group, aggregation is taking a couple of seconds.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...