mongodb:如果不存在则插入


问题内容

每天,我都会收到一堆文件(更新)。我想做的是插入每个尚不存在的项目。

  • 我还想跟踪我第一次插入它们以及上次在更新中看到它们的情况。
  • 我不想有重复的文件。
  • 我不想删除以前已保存但不在我的更新中的文档。
  • 每天有95%(估计)的记录未修改。

我正在使用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)

我的问题是它非常慢(不到10万条记录需要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块。如果密钥不存在,它将插入;如果密钥不存在,它将更新。

之前:

{"key":"value", "key2":"Ohai."}

后:

{"key":"value", "key2":"value2", "key3":"value3"}

您还可以指定要写入的数据:

data = {"$set":{"key2":"value2"}}

现在,您选择的文档将仅更新“ key2”的值,而其他所有内容保持不变。