每天,我都会收到一批文件(更新)。我想要做的是插入每个不存在的项目。
我正在使用 Python 驱动程序 (pymongo)。
我目前做的是(伪代码):
for each document in update:
existing_document = collection.find_one(document)
if not existing_document:
document['insertion_date'] = now
else:
document = existing_document
document['last_update_date'] = now
my_collection.save(document)
我的问题是它非常慢(少于 100 000 条记录需要 40 分钟,而我有数百万条记录在更新中)。 我很确定有一些内置的东西可以做到这一点,但是 update() 的文档是 mmmhhh....有点简洁.... (http://www.mongodb.org/display/DOCS/Updating)
有人可以建议如何更快地做到这一点吗?
最佳答案
听起来你想做一个 upsert
。 MongoDB 对此具有内置支持。向 update()
调用传递一个额外参数:{upsert:true}
。例如:
key = {'key':'value'}
data = {'key2':'value2', 'key3':'value3'};
coll.update(key, data, upsert=True); #In python upsert must be passed as a keyword argument
这将完全替换您的 if-find-else-update block 。如果 key 不存在,它将插入,如果存在,它将更新。
之前:
{"key":"value", "key2":"Ohai."}
之后:
{"key":"value", "key2":"value2", "key3":"value3"}
您还可以指定要写入的数据:
data = {"$set":{"key2":"value2"}}
现在您选择的文档将仅更新 key2
的值,而其他所有内容都保持不变。
https://stackoverflow.com/questions/2801008/