Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of key values in mongoDb [duplicate]

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.

like image 238
Yashodhan K Avatar asked Dec 20 '13 10:12

Yashodhan K


People also ask

Can a MongoDB document contain duplicate keys?

Its not possible to store a document in MongoDB with two fields with the same key at the same level. The second key will overwrite the first.

Does MongoDB guarantee order?

MongoDB only gurantee order of documents based on a sort operation. Therefore, even if some queries will return the order you need it won't be guaranteed for every query.


1 Answers

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.

like image 168
Makis Tsantekidis Avatar answered Sep 20 '22 06:09

Makis Tsantekidis