6

mongo code :

db.temperature.insert({"x":3,"y":4});

db.temperature.find();

OUTPUT { "_id" : ObjectId("52b418fb132c1f3236831447"), "y" : 4, "x" : 3 }

Please help me to understand why in my case(above.) The find method is showing Y value first and x value later even when while inserting the order is different.

Appreciate any help.

Community
  • 1
  • 1
Yashodhan K
  • 160
  • 1
  • 9

1 Answers1

6

Quoting https://stackoverflow.com/a/6453755/1150636

Both document structure and collection structure in MongoDB based on JSON principles. JSON is a set of key/value pairs (in particular fieldName/fieldValue for document and index/document for collection). From this point of view it doesn't seem that you can rely on order at all.

This means that there is no particular order that mongodb is required to return the fields of one record. You need to be ready to parse the results in whichever order they may be returned.

Michael Mior
  • 28,107
  • 9
  • 89
  • 113
Makis Tsantekidis
  • 2,698
  • 23
  • 38
  • What concept of architecture makes ordering unsure? I suppose even sharding does not decouple unit document. – Yashodhan K Dec 23 '13 at 11:47
  • if you wish to delve into why JSON is unordered you can look at [the specification of JSON](http://www.json.org/). From that specification: `An object is an unordered set of name/value pairs.` – Makis Tsantekidis Dec 25 '13 at 17:54
  • Order of keys can matter in mongo, certain find queries will return some results or no results depending on the order of the keys. See http://devblog.me/wtf-mongo for example, and if the link ever dies, find it on wayback machine. – Kevin Wheeler Sep 03 '16 at 06:00
  • 2
    But, how about querying w.r.t. compound index? https://docs.mongodb.com/manual/tutorial/sort-results-with-indexes/#sort-on-multiple-fields It says {a:1, b:1} and {b:1,a:1} are different. How mongo ensures this? – Praveen Feb 07 '17 at 20:08