简体   繁体   中英

Preserve key-value order of mongo document using Pymongo

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.

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)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM