2

I'm sure this is an easy one, but I just wanted to make sure. Is find() with some search and projection criterion same as applying a sort({$natural:1}) on it?

Also, what is the default natural sort order? How is it different from a sort({_id:1}), say?

gravetii
  • 9,273
  • 9
  • 56
  • 75

2 Answers2

3

db.collection.find() has the result as same as db.collection.find().sort({$natural:1})

{"$natural" : 1} forces the find query to do a table scan (default sort), it specifies hard-disk order when used in a sort.

When you are updating your document, mongo could move your document to another place of hard-disk.

for example insert documents as below

{
    _id : 0, 
},
{
    _id : 1, 
}

then update:

db.collection.update({ _id : 0} , { $set : { blob : BIG DATA}})

And when you perform the find query you will get

{
    "_id" : 1
},
{
    "_id" : 0,
    "blob" : BIG DATA
}

as you see the order of documents has changed => the default order is not by _id

Disposer
  • 6,201
  • 4
  • 31
  • 38
  • So that means, say if I have made a `find()` query on a production setup and then have a cursor for that, and then after a few days, I do another `find()` and get another cursor, the order of documents will be different in both these cursors? of course assuming that there were quite a few updates to the documents. – gravetii Jan 01 '15 at 11:36
  • If you update your documents and if the update query cause to move some of those, yes you will get different result (different in order). – Disposer Jan 01 '15 at 11:39
1

If you don't specify the sort then mongodb find() will return documents in the order they are stored on disk. Document storage on disk may coincide with insertion order but thats not always going to be true. It is also worth noting that the location of a document on disk may change. For instance in case of update, mongodb may move a document from one place to another if needed.

In case of index - The default order will be the order in which indexes are found if the query uses an index.

The $natural is the order in which documents are found on disk.

It is recommended that you specifiy sort explicitly to be sure of sorting order.

Abhay PS
  • 4,015
  • 5
  • 25
  • 32