4

I am using PyMongo to insert data (title, description, phone_number ...) into MongoDB. However, when I use mongo client to view the data, it displays the properties in a strange order. Specifically, phone_number property is displayed first, followed by title and then comes description. Is there some way I can force a particular order?

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Muhammad Waqar
  • 849
  • 2
  • 13
  • 29

2 Answers2

6

The above question and answer are quite old. Anyhow, if somebody visits this I feel like I should add:

This answer is completely wrong. Actually in Mongo Documents ARE ordered key-value pairs. However when using pymongo it will use python dicts for documents which indeed are not ordered (as of cpython 3.6 python dicts retain order, however this is considered an implementation detail). But this is a limitation of the pymongo driver.

Be aware, that this limitation actually impacts the usability. If you query the db for a subdocument it will only match if the order of the key-values pairs is correct.

Just try the following code yourself:

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 gets executed the 'same' document is added to the collection. Thus, each time we run this code snippet the printed value 'should' increase by one. It does not because find only maches subdocuemnts with the correct ordering but python dicts just insert the subdoc in arbitrary order.

see the following answer how to use ordered dict to overcome this: https://stackoverflow.com/a/30787769/4273834

squanto773
  • 494
  • 5
  • 12
4

Original answer (2013):

MongoDB documents are BSON objects, unordered dictionaries of key-value pairs. So, you can't rely on or set a specific fields order. The only thing you can operate is which fields to display and which not to, see docs on find's projection argument.

Also see related questions on SO:

Hope that helps.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Please consider again this answer - as pointed out by @squanto773 https://stackoverflow.com/a/39778410/248616 – Nam G VU Jan 20 '18 at 05:55