The above question and answer is quite old. Anyway, if someone visits this, I feel I have to add:
This answer is completely incorrect. In fact, key-value pairs are ordered in Mongo Documents ARE. However, when using pymongo, it will use python dicts for documents that are not really ordered (since cpython 3.6 python dicts keeps order, however this is considered an implementation detail). But this is a limitation of the pymongo driver.
Remember that this limitation actually affects usability. If you request db for a subdocument, it will only match if the order of the key-value pairs is correct.
Just try the following code:
from pymongo import MongoClient db = MongoClient().testdb col = db.testcol subdoc = { 'field1': 1, 'field2': 2, 'filed3': 3 } document = { 'subdoc': subdoc } col.insert_one(document) print(col.find({'subdoc': subdoc}).count())
Each time this code is run, the "same" document is added to the collection. Thus, every time we run this piece of code, the printed value "should" increase by one. This is not because find only intercepts subdocuemnts with the correct order, but python dicts just inserts the subdoc in random order.
see the following answer on how to use an ordered dict to overcome this: fooobar.com/questions/449510 / ...
source share