1

Am trying to read a document from mongodb using pymongo, with the order key values maintained, as mentioned in this link.

from bson import CodecOptions, SON
opts = CodecOptions(document_class=SON)
collect = db.get_collection(type)
coll = collect.with_options(codec_options=opts)
cursor = coll.find({'abc': 'xyz'})

But still the key-value order is not maintained in the result of find() query. Any suggestions/work-around to fix this problem?

EDIT: Basically I mean the document I get from mongo find query should be as it is. should not change the order.

user3366706
  • 1,529
  • 3
  • 31
  • 54

1 Answers1

1

it works just fine with me in pymongo (3.0.3):

  • probably you did not used SON when inserting the documents ?
  • tip: you can specify SON as document_class in MongoClient as described here then all documents will be retrieved as SON objects

from bson import CodecOptions, SON
docson= SON([(j,i) for i,j in enumerate('abcdefghijklmnopqrstuvwxyz')])
docson
SON([('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6), ('h', 7), ('i', 8), ('j', 9), ('k', 10), ('l', 11), ('m', 12), ('n', 13), ('o', 14), ('p', 15), ('q', 16), ('r', 17), ('s', 18), ('t', 19), ('u', 20), ('v', 21), ('w', 22), ('x', 23), ('y', 24), ('z', 25)])
db.test.insert_one(docson)
opts = CodecOptions(document_class=SON)
colson = db.test.with_options(codec_options=opts)
colson.find_one({'a': 0})
SON([(u'_id', ObjectId('55c92bc2993000171429eff6')), (u'a', 0), (u'b', 1), (u'c', 2), (u'd', 3), (u'e', 4), (u'f', 5), (u'g', 6), (u'h', 7), (u'i', 8), (u'j', 9), (u'k', 10), (u'l', 11), (u'm', 12), (u'n', 13), (u'o', 14), (u'p', 15), (u'q', 16), (u'r', 17), (u's', 18), (u't', 19), (u'u', 20), (u'v', 21), (u'w', 22), (u'x', 23), (u'y', 24), (u'z', 25)])
nickmilon
  • 1,332
  • 1
  • 10
  • 9
  • opts = CodecOptions(document_class=SON) colson = db.test.with_options(codec_options=opts) is not helping, I think it works only from pymongo shell..? – user3366706 Aug 10 '15 at 23:54
  • @user3366706 no it works with pymongo my example is python nothing to do with shell. It works provided the documents you inserted were SON objects too. – nickmilon Aug 11 '15 at 00:11
  • yeah, sorry to bug you guys.. it was a problem in someother part of code, i mean i was using json_util.dumps and loads on the query result which caused the order of key-values to change.. actually the code in the question itself works fine now... thanks for your time... – user3366706 Aug 11 '15 at 00:54
  • using json_util over the query result is the actual problem – user3366706 Aug 11 '15 at 00:56