Change the display order of properties in MongoDB

I use PyMongo to insert data (title, description, phone_number ...) into MongoDB. However, when I use the mongo client to view the data, it displays the properties in a weird order. In particular, the phone_number property is displayed first, then title and then description . Is there a way I can force a specific order?

+4
source share
2 answers

Original answer (2013):

MongoDB documents are BSON objects, unordered dictionaries of key-value pairs. Thus, you cannot rely or establish a specific field order. The only thing you can use is which fields to display and which not, see the docs for find projection .

Also see related questions on SO:

Hope this helps.

+4
source

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 / ...

+4
source

Source: https://habr.com/ru/post/1478871/


All Articles