How to get ordered dictionaries in pymongo?
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)])]
This solution above is correct for older versions of MongoDB and the pymongo driver but it no longer works with pymongo3 and MongoDB3+ You now need to add document_class=OrderedDict
to the MongoClient constructor. Modifying the above answer for pymongo3 compatibility.
from collections import OrderedDict
from pymongo import MongoClient
import bson
client = MongoClient(document_class=OrderedDict)
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})))
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})))
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)])]