我正在研究 pymongo,这是我的文档:
{
"_id": ObjectId("51211b57f07ddaa377000000"),
"assignments": {
"0": {
"0": {
"_id": ObjectId("5120dd7400a4453d58a0d0ec")
},
"1": {
"_id": ObjectId("5120dd8e00a4453d58a0d0ed")
},
"2": {
"_id": ObjectId("5120ddad00a4453d58a0d0ee")
}
}
},
"password": "my_passwd",
"username": "john"
}
我想取消设置所有此类文档的“分配”属性。 我可以通过以下方式在 mongo shell 上实现这一点:
db.users.update({}, {$unset: {"assignments": 1}}, false, true)
即,我将 upsert 和 multi 标志作为最后两个参数传递给用户集合上的更新函数函数。 但是我用 pymongo 做到了这一点:
db.users.update({}, {"$unset": {"assignments": 1}}, False, True)
但是python解释器报错如下:
File "notes/assignment.py", line 34, in <module>
db.users.update({}, {"$unset": {"assignments": 1}}, False, True)
File "/usr/local/lib/python2.7/dist-packages/pymongo/collection.py", line 481, in update
check_keys, self.__uuid_subtype), safe)
File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 852, in _send_message
rv = self.__check_response_to_last_error(response)
File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 795, in __check_response_to_last_error
raise OperationFailure(details["err"], details["code"])
pymongo.errors.OperationFailure: Modifiers and non-modifiers cannot be mixed
我哪里错了?
最佳答案
问题在于您传入的两个标志不是 upsert
和 multi
。根据 PyMongo 的 Collection.update
的文档(找到 here ),看起来您可能正在传递 upsert
和 manipulate
的值> 选项,虽然我不确定。
要解决这个问题,您所要做的就是使用 Python 最棒的功能之一:命名参数。通过指定要传递给 update
的选项,除了确保不会发生此类事故之外,还可以增加代码的清晰度。
在这种情况下,我们要传递选项 upsert=False
和 multi=True
。
db.users.update({}, { "$unset": { "assignments": 1 } }, upsert=False, multi=True)
关于python - pymongo 中的 Upsert 和 Multi 标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14925134/