0

Let's say we have a collection of invoices and that we query and sort by sales date.

There can of course be many invoices on the same date.

Does Mongo provide any guarantee consistent order of the invoices for the same date?

e.g. does it also provide a default sort on say _id, or is the behavior described as undefined?

If one were to run the same query multiple times, would the invoices on the same date come in the same order each time? Or is it up to the developer to also provide a secondary sort property, eg. _id. ?

To me, it looks like it is consistent, but can I really count on that?

Roger Johansson
  • 22,764
  • 18
  • 97
  • 193

1 Answers1

0

1.Does Mongo provide any guarantee consistent order of the invoices for the same date?

Yes, results will be consistent all the time

  1. Does it also provide a default sort on say _id, or is the behavior described as undefined?

By default all records will be sorted by `_id`, that's why i can say Yes to your first question.

  1. If one were to run the same query multiple times, would the invoices on the same date come in the same order each time?

yes, always

  1. is it up to the developer to also provide a secondary sort property, eg. _id. ?

yes

For my experiment results check attached screenshots.

Decrement order sorting without _id index Increment order sorting without _id index Increment order sorting with _id index Decrement order sorting with _id index

Ankur
  • 496
  • 1
  • 6
  • 11
  • Are you sure this is right? [This](https://stackoverflow.com/a/33018164/8646838) may change your mind – Rakshith Murukannappa Jul 24 '19 at 08:13
  • 1
    The order of results with identical sort keys (for example, the same sale date) is not defined. Invoices 1, 2, and 3 with the same sale date could appear in any order and would still be correct according to the sort criteria of "sale date". To guarantee sort order you need a unique sort key (for example, sale date plus invoice number). The natural order of results returned by the MongoDB server is also [undefined](https://stackoverflow.com/a/11599283/1388319). Your experiments testing with a UI tool may describe the outcome if that tool adds a sort order, but that isn't the default behaviour. – Stennie Jul 24 '19 at 11:13
  • Yes i think it may be results came as expected because of UI tool. – Ankur Jul 24 '19 at 11:25