How to get ordered dictionaries in pymongo?

前端 未结 4 785
忘了有多久
忘了有多久 2020-11-30 09:59

I am trying get ordered dictionaries in Pymongo. I have read it can be done with bson.son.Son. The Docs are Here

However, I can\'t seem to make it work. There is

4条回答
  •  生来不讨喜
    2020-11-30 10:45

    A standard find() in PyMongo will not return an object who's fields are in the same order as that object, if you retrieved it via mongo shell.

    This is because, the default type returned is a Dict and the order is not defined.

    You can use SON as suggested. Here is how I did it. Now the field order will be respected.

    This is for pymongo==3.4.0

    from bson.codec_options import CodecOptions
    from bson.son import SON
    
    opts = CodecOptions(document_class=SON)
    collection_son = mongo.db.collection.with_options(codec_options=opts)
    
    collection_son.find_one({"imsid": '12345'})
    

提交回复
热议问题