【问题标题】:MongoDB: Insert multiple documents into collection with unique index even if some violate the indexMongoDB:将多个文档插入具有唯一索引的集合中,即使有些文档违反了索引
【发布时间】:2017-03-24 03:22:16
【问题描述】:

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

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);
    }
  })

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

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

因此,即使只有一个文档违反了唯一索引,也没有保存任何文档。

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

【问题讨论】:

    标签: node.js mongodb unique mongojs database


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2017-08-16
      • 2016-12-15
      • 2015-08-16
      • 2014-02-23
      • 2016-03-15
      • 2020-07-12
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多