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)])]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…