Aggregate $group then $limit queries on large datasets

I have a dataset of 3 million documents and I want to perform a $group query.

I find that if $sort before I $group my query only touches the indexes it goes pretty fast - but if my query looks at the contents of the documents it takes forever. Worse, if I attempt to $match to reduce the query size it goes slower - even though my $match is on the same index as the $sort.

Are there some way to coax mongo into handling $group gueries better? For example can I hit to the $group that the records are in-order so that it knows what once it finds a document that belongs to a different group that the previous group is complete?

Hi @Matthew_Shaylor ,

Welcome to MongoDB community.

The official way of optimizing group stages is by sorting and then Grouping based on appropriate index:

Now if you match and group it will work if the order of the fields is Equality Sort Range. Since you group I believe there might be range or other fields not in that order, additionally make sure to add a sort by the index between match and group.

Otherwise I need an explain plan and your indexes to assist further.

Thanks
Pavel