为什么,怎么会这样?在
item = db.test.find_one()
result = db.test.replace_one(item, item)
print(result.raw_result)
# Gives: {u'n': 1, u'nModified': 1, u'ok': 1, 'updatedExisting': True}
print(result.modified_count)
# Gives 1
当mongodb shell中的等价物总是0时
^{pr2}$我怎样才能得到一致的结果,并正确地检测到替换者实际上在更改数据?在
这是因为MongoDB以二进制(BSON)格式存储文档。BSON文档中的键值对可以有任何顺序(除了\u id总是第一个)。 让我们先从mongo shell开始。mongoshell在读写数据时保留键顺序。 例如:
如果使用此文档值执行replaceOne(),则会避免修改,因为存在现有的BSON。在
^{pr2}$但是,如果更改字段的顺序,它将检测到修改
让我们进入Python世界。PyMongo默认情况下将BSON文档表示为Python字典,Python字典中的键顺序没有定义。因此,您无法预测它将如何序列化到BSON。根据您的例子:
如果对您的用例很重要,一种解决方法是使用bson.SON。例如:
您还可以看到
bson.SON
在PyMongo(v3.3.0)中使用,即_update() method。另请参阅相关文章:PyMongo and Key Order in SubDocuments。在更新回答另一个问题:
据我所知,没有一个“标准”函数可以将嵌套字典转换为子字典。尽管您可以自己编写一个自定义的
dict
到SON
转换器,例如:或者使用bson作为中间格式
一旦采用
SON
格式,就可以使用SON.to_dict()转换回Python字典相关问题 更多 >
编程相关推荐