3

I'm using python 3.5.2 and pymongo while trying to store a dict to mongodb

 data = {'A':1,'B':2,'C':3}
 test = {'A':data['A'], 'B':data['B'], 'C':data['C']}
 x = mycol.insert_one(test) #mycol is the name of my collection

But the order of the dict is not preserved while inserting the document into the DB. When i run

print(mycol.find_one())

I get

{'A':1, 'C':3, _id': ObjectId('xxxxxx10f389f63bf0c8bfba'), 'B':2}

instead of

{ _id': ObjectId('xxxxxx10f389f63bf0c8bfba'), 'A':1, 'B':2, 'C':3}

But i was able to preserve the order when i ran it on a system with python 3.6.2. Is the version of python the issue or can i fix it on python 3.5.2 itself?

Sharat Chandra
  • 191
  • 1
  • 11
  • have you tried using .insert(test) instead in the older version of python? – mgracer Oct 03 '18 at 06:58
  • Yep tried that, same result; order is getting messed up – Sharat Chandra Oct 03 '18 at 07:12
  • 1
    Consider this: https://stackoverflow.com/questions/25480089/right-way-to-initialize-an-ordereddict-using-its-constructor-such-that-it-retain – Janne Karila Oct 03 '18 at 09:23
  • @JanneKarila I actually can't use a list like that while inserting documents to mongodb. I've updated my post and removed the OrederedDict. The problem still persists on my system but the other system still prints it in the order mentioned – Sharat Chandra Oct 03 '18 at 12:04

0 Answers0