MongoDB: Insert multiple documents into collection with unique index even if some violate the index

让人想犯罪 __ 提交于 2019-12-11 07:55:58

问题


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 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.

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


回答1:


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/



来源:https://stackoverflow.com/questions/42990854/mongodb-insert-multiple-documents-into-collection-with-unique-index-even-if-som

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!