1

Basic question. Does mongodb find command will always return documents in the order they where added to collection? If no how is it possible to implement selection docs in the right order? Sort? But what if docs where added simultaneously and say created date is the same, but there was an order still.

WHITECOLOR
  • 24,996
  • 37
  • 121
  • 181
  • 1
    Does http://stackoverflow.com/questions/11599069/what-does-mongo-sort-on-when-no-sort-order-is-specified/11599283 answer your question? – WiredPrairie Mar 17 '13 at 23:03

1 Answers1

2

Well, yes and ... not exactly. Documents are default sorted by natural order. Which is initially the order the documents are stored on disk, which is indeed the order in which the documents had been added to a collection. This order however, is not deterministic, as document may be moved on disk once these documents grow after update operations, and can't be fit into current space anymore. This way the initial (insert) order may change.

The way to guarantee insert order sort is sort by {_id : 1} as long as the _id is of type ObjectId. This will return your documents sorted in ascending order.

Write operations do not take place simultaneously. Write locks are imposed in database level (V 2.4 and on). The first four bytes of _id is insert timestamp, and 3 last digits is a random counter used to distinguish (and sort) between ObjectId instances with same timestamp.

_id field is indexed by default

Ori Dar
  • 18,687
  • 5
  • 58
  • 72