假设我有以下MongoDB集合(我在本例中使用mongomock,因此很容易重现):
import mongomock
collection = mongomock.MongoClient().db.collection
objects = [{'name': 'Alice', 'age': 21}, {'name': 'Bob', 'age': 20}]
collection.insert_many(objects)然后我想用一些新对象中的字段来更新我现有的对象:
new_objects = [{'name': 'Alice', 'height': 170}, {'name': 'Caroline', 'height': 160}]我能想到的唯一方法是:
for record in new_objects:
if collection.find_one({'name': record['name']}) is not None:
collection.update_one({'name': record['name']}, {'$set': {'height': record['height']}})
else:
collection.insert_one(record)但是,如果new_objects非常大,那么这个方法就会变得很慢--有没有办法使用update_many来解决这个问题呢?
发布于 2020-07-24 22:04:07
你不能使用update_many(),因为它需要一个单独的过滤器,但在你的用例中不会工作,因为每个过滤器都是不同的。
一个更简单的结构使用upsert=True来避免插入/更新逻辑,并且还设置了记录中指定的所有字段,这减少了代码:
for record in objects + new_objects:
collection.update_one({'name': record.get('name')}, {'$set': record}, upsert=True)如果更新次数过多,速度会变慢,请确保在name字段上有一个索引(在mongo shell中):
db.collection.createIndex( { "name": 1 } )您可以通过使用bulk_write操作来获得更高的性能。工作示例:
from pymongo import MongoClient, UpdateOne
collection = MongoClient().db.collection
objects = [{'name': 'Alice', 'age': 21}, {'name': 'Bob', 'age': 20}]
new_objects = [{'name': 'Alice', 'height': 170}, {'name': 'Caroline', 'height': 160}]
updates = []
for record in objects + new_objects:
updates.append(UpdateOne({'name': record.get('name')}, {'$set': record}, upsert=True))
collection.bulk_write(updates)
for record in collection.find({}, {'_id': 0}):
print(record)提供:
{'name': 'Alice', 'age': 21, 'height': 170}
{'name': 'Bob', 'age': 20}
{'name': 'Caroline', 'height': 160}https://stackoverflow.com/questions/63057067
复制相似问题