我正在尝试更新存储在MongoDB中的记录/对象的所有属性,现在我正在尝试这样做。
这是对的吗?或者他们使用pymongo
做什么在目标之上?
mongo_object = {
_id : 123,
prop_key_1: some_value,
// ... many present
prop_key_n: some_value,
}
def delete(record):
doc = get_db().reviews.delete_many({"id" : record["_id"]})
print(doc.deleted_count)
# all key values are changed, mongo_object is changed except the id.
delete(mongo_object)
db.collection_name.insert_one(mongo_object)
但是上面的代码没有删除对象,doc.deleted_count
是0。
答案 0 :(得分:1)
from bson.objectid import ObjectId
def replace_one(record):
result = client.test_db.test_collection.replace_one({"_id":ObjectId(record["_id"])}, record,upsert=True)
print(result.matched_count)
What is the correct way to query MongoDB for _id using string by using Python?
Pymongo doc - http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.replace_one
答案 1 :(得分:1)
db.collection_name.update_one({"_id" : record["_id"]}, new_data}
只使用不带$ set的更新,文档将被完全替换而不更改_id