node.js - MongoDB insertMany并跳过重复项
问题描述
我正在尝试将insertMany()
项目添加到我的 Mongo 数据库中,但我想跳过重复的 ID。
我正在使用Node.js
和mongodb
。
我有一些数据:
const myExampleData = [
{_id:'someId1', name:'I am example'},
{_id:'someId2', name:'I am second example'}
];
我想像这样插入它们:
dbo.collection(collectionName).insertMany(myExampleData).catch(err=>{
console.error(err);
});
让我们假设它someId1
已经存在。我不想覆盖它。我只是想跳过它。在当前情况下,它不会插入someId2
. 一旦抛出重复异常,它就会停止。
有没有办法插入许多并跳过重复项?
可能的问题重复。
我发现线程MongoDB insert without duplicates where 建议使用update()
withupsert
而不是insert()
which 可能适用于一项。但是有多少项目呢?据我所知updateMany()
,会用相同的值更新所有过滤的行,但我想插入不同的值。
解决方案
Checking in your statement :
Lets suppose that someId1 already exists. I don't want to override it. I just want to skip it.
So you just wanted to skip duplicate docs as your intention is not update duplicate docs with latest data - So there is no need to use .update()
, You can still do this using .insertMany() by passing in a flag ordered
in options to query :
Ordered : Optional. A boolean specifying whether the mongod instance should perform an ordered or unordered insert. Defaults to true.
db.collection.insertMany(
[ <document 1> , <document 2>, ... ],
{
ordered: <boolean>
}
)
Your code :
dbo.collection(collectionName).insertMany(myExampleData, {ordered : false }).catch(err=>{
console.error(err);
})
As if you're checking against _id
which will have default unique index & any incoming duplicates will actually throw an error, With ordered : false
we're making this insertion operation un-ordered by that we're skipping all the incoming duplicates & proceeding further with out actually throwing any errors.
推荐阅读
- java - JGit:如何在创建 Git 存储库并将其推送到 GitHub 时修复 NoRemoteRepositoryException?
- javascript - javascript计算没有空值的对象数组中的对象
- javascript - 如何拟合标记
- reactjs - NextJS & CSS SyntaxError: Unexpected token
- python - 无法使用 .widget.attrs.update 将 CSS 类添加到我的 CharField
- kotlin - Kotlin distinctBy 有条件
- xml - 范围内属性的 XSLT 映射值
- java - 将横幅添加到应用程序时,应用程序崩溃
- ruby-on-rails - 即使它已经由设计构建,如何在 Rails 中添加角色和权限
- c# - C# 是否将结构数组分配为内存中的数组结构?