Indexes not ordered correctly

Hello there!

So I’ve been changing my _id from “string-ints” to actual NumberLong values…

This way, I’ve been trying to reIndex the collection which contains over 900k documents so they are ordered by descending number, 1 being the first and Int64 the last…

However, when I check out db.Collection.find() with mongo, it prints them out all randomly, for example: 3, 5, 1, 4, 2

Is it just the db.Collection.find() that makes them look like it or are they actually all random?
If they are all random, is there a way to fix that?

Thanks

Welcome to the community @Sylmat_gaming!

If you haven’t explicitly specified the order of results using sort() criteria, the default order is undefined outside of the special case of capped collections. This is called natural order.

For more details see: How does MongoDB sort records when no sort order is specified?.

Include sort() criteria:

db.Collection.find().sort({_id:1})

For more tips on sorting efficiently, see: Use Indexes to Sort Query Results. This example of sorting on _id without any filter criteria will be able to use the _id index, which is a required index automatically created for MongoDB collections.

Regards,
Stennie

1 Like

So does it mean that in the database they are all sorted by descending order?

Hi @Sylmat_gaming,

The natural order of documents at the storage layer is generally not defined except for the special case of capped collections (which has associated usage restrictions, like disallowing direct document deletion).

If you want results in an expected order, you need to provide explicit sort() criteria.

Otherwise results will be returned in the most efficient path (i.e. “as they are found”) and the implementation is not required to provide any strict ordering. You can see this empirically in your own results: the natural order is not deterministic.

It means that there is no expected result ordering unless you explicitly request one. The value of the primary key does not determine the physical ordering of documents in storage.

Regards,
Stennie

1 Like

Fair enough, thanks :smiley:

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.