首页 > 解决方案 > MongoDB insertMany并跳过重复项

问题描述

我正在尝试将insertMany()项目添加到我的 Mongo 数据库中,但我想跳过重复的 ID。
我正在使用Node.jsmongodb

我有一些数据:

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(),会用相同的值更新所有过滤的行,但我想插入不同的值。

标签: node.jsmongodbmongodb-query

解决方案


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.


推荐阅读