Home > Mobile >  will documents be returned in the order of the compound index?
will documents be returned in the order of the compound index?

Time:12-31

Suppose that this is my compound index in my MongoDB collection:

{
  "age": 1,
  "income": 1,
}

Will all returned records be sorted first by age and then by income?

CodePudding user response:

That is not guaranteed. Each MongoDB node will return the documents in the order they are encountered. This means that if the query uses an index to select documents, they will be encountered in the order they appear in the index.

This will result in the results being sorted as long as the database is a single-node, or a single replica set.

However, if this is run on a sharded cluster, each shard will return the results ordered by the index, but these per-shard result sets will be combined at the mongos in the order they happen to arrive.

This means that you may be in for a nasty surprise when your results are no longer returned in a stable order when your application becomes popular enough that you have to scale up to a sharded cluster.

It would be better in the long run to explicitly add a sort to the request. In the case of the single-node or single-replica set it will not add any extra overhead to an index-serviced query, but it will help to future-proof your code.

  • Related