Aggregate do not return records in order as they are inserted

Viewed 46

I am facing one issue with aggregate query.

When I am trying to retrieve records using aggregate ($match), I am not receiving records in same order they are inserted.

but when I am trying to query using find, then I am getting data in same order data inserted.

1 Answers

In Mongo, the default internal sort order is an "unknown" implementation detail.

If a certain order was required then you should use the $sort stage otherwise it's considered overhead operation for the storage engine

Without any query criteria, results will be returned by the storage engine in their "natural order" or in layman term the order which they were found, however we don't really know what that order is and we shouldn't rely on it.

So obviously the simple option would be to add a $sort stage on _id for example, if for some reason you don't have a field you can sort on you can use $natural that will return results in the order you expect.

Related