MongoDB:将多个文档插入具有唯一索引的集合中,即使某些文档违反索引 [英] MongoDB: Insert multiple documents into collection with unique index even if some violate the index

查看:175
本文介绍了MongoDB:将多个文档插入具有唯一索引的集合中,即使某些文档违反索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将文档数组插入MongoDB集合中.该集合在其中一个字段上具有唯一索引.我要一次插入所有文档:

I am trying to insert an array of documents into a MongoDB collection. The collection has a unique index on one of the fields. I am inserting all the documents at once as such:

const mongojs = require('mongojs');
const db = mongojs('mongodb://username:password@address.mlab.com:37230/database');

             // documents is an array of documents
db.items.insert(documents, (err, task) => {
    if (err) {
      console.log(err);
    }
  })

现在有一个违反唯一索引的文档,我收到此错误:

Now there is one document that violates the unique index and I receive this error:

E11000重复键错误索引:database.items.$ upc_1重复键:

E11000 duplicate key error index: database.items.$upc_1 dup key:

因此,即使只有一个违反唯一索引的文档,也不会保存任何文档.

Consequently, NONE of the documents get saved even though there was only one document that violated the unique index.

我如何告诉Mongo忽略该文档并保存所有其他文档?谢谢!

How do I tell Mongo to just ignore that one document and save all the others? Thanks!

推荐答案

您可以将db.collection.insertMany()函数与参数{ordered: false}一起使用.请参阅文档(在底部描述无序插入的底部附近): https ://docs.mongodb.com/manual/reference/method/db.collection.insertMany/

You can use the db.collection.insertMany() function with the parameter {ordered: false}. See the docs (near the bottom where they describe unordered inserts): https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/

这篇关于MongoDB:将多个文档插入具有唯一索引的集合中,即使某些文档违反索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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