mongodb通过唯一键插入或更新多个文档 [英] mongodb multiple documents insert or update by unique key

查看:77
本文介绍了mongodb通过唯一键插入或更新多个文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定期从外部资源获取项目列表并将它们保存到集合中.

I would like to get a list of items from an external resource periodically and save them into a collection.

有几种可能的解决方案,但都不是最优的,例如:

There are several possible solutions but they are not optimal, for example:

  1. 删除整个集合并保存新的项目列表

  1. Delete the entire collection and save the new list of items

使用find({})"从集合中获取所有项目,并使用它过滤掉现有项目并保存不存在的项目.

Get all items from the collection using "find({})" and use it to filter out existing items and save those that do not exist.

但更好的解决方案是设置一个唯一键,然后执行某种更新或插入".现在在保存项目时,唯一键已经存在,我会收到一个错误有没有办法做到这一点?

But a better solution will be to set a unique key and just do kind of "update or insert". Right now on saving items the unique key already exists I will get an error is there a way to do it at all?

**upsert 不会做这项工作,因为它用相同的值更新所有项目,所以它实际上只适用于单个文档

**upsert won't do the work since it's updating all items with the same value so it's actually good for a single document only

推荐答案

我有一种感觉,你可以通过使用普通"insertMany,其中 ordered 选项设置为 false.文档指出

I have a feeling you can achieve what you want simply by using the "normal" insertMany with the ordered option set to false. The documentation states that

注意插入了一个文档:_id的第一个文档:13将成功插入,但第二次插入将失败.这会还阻止插入队列中剩余的其他文档.order 为 false 时,插入操作将继续执行任何剩余文件.

Note that one document was inserted: The first document of _id: 13 will insert successfully, but the second insert will fail. This will also stop additional documents left in the queue from being inserted. With ordered to false, the insert operation would continue with any remaining documents.

所以你会得到重复键"异常,但是,你可以在你的情况下简单地忽略.

So you will get "duplicate key" exceptions which, however, you can simply ignore in your case.

这篇关于mongodb通过唯一键插入或更新多个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆