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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…