How does MongoDB order their docs in one collection? [duplicate]

It’s called natural order:

natural order

The order in which the database refers to documents on disk. This is the default sort order. See $natural and Return in Natural Order.

This confirms that in general you get them in the same order you inserted, but that’s not guaranteed–as you noticed.

Return in Natural Order

The $natural parameter returns items according to their natural order within the database. This ordering is an internal implementation feature, and you should not rely on any particular structure within it.

Index Use

Queries that include a sort by $natural order do not use indexes to fulfill the query predicate with the following exception: If the query predicate is an equality condition on the _id field { _id: <value> }, then the query with the sort by $natural order can use the _id index.

MMAPv1

Typically, the natural order reflects insertion order with the following exception for the MMAPv1 storage engine. For the MMAPv1 storage engine, the natural order does not reflect insertion order if the documents relocate because of document growth or remove operations free up space which are then taken up by newly inserted documents.

Obviously, like the docs mentioned, you should not rely on this default order (This ordering is an internal implementation feature, and you should not rely on any particular structure within it.).

If you need to sort the things, use the sort solutions.


Basically, the following two calls should return documents in the same order (since the default order is $natural):

db.mycollection.find().sort({ "$natural": 1 })
db.mycollection.find()

If you want to sort by another field (e.g. name) you can do that:

db.mycollection.find().sort({ "name": 1 })

Leave a Comment