How to get ordered dictionaries in pymongo?

前端 未结 4 775
忘了有多久
忘了有多久 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:31

    You can use bson.son.SON or OrderedDict to store ordered dict.

    And retrive data with as_class=OrderedDict option.

    Here is an example:

    from collections import OrderedDict
    from pymongo import MongoClient
    import bson
    
    client = MongoClient()
    sample_db = client['sample']
    test_col = sample_db['test']
    
    test_col.drop()
    
    data = OrderedDict([("one", 1), ("two", 2), ("three", 3), ("four", 4)])
    test_col.insert(data)
    print(list(test_col.find({}, {'_id': 0}, as_class=OrderedDict)))
    
    test_col.drop()
    
    data = bson.son.SON([("one", 1), ("two", 2), ("three", 3), ("four", 4)])
    test_col.insert(data)
    print(list(test_col.find({}, {'_id': 0}, as_class=OrderedDict)))
    

    Output:

    [OrderedDict([(u'one', 1), (u'two', 2), (u'three', 3), (u'four', 4)])]
    [OrderedDict([(u'one', 1), (u'two', 2), (u'three', 3), (u'four', 4)])]
    

提交回复
热议问题