【问题标题】:Inserting Multiple Documents into MongoDB while Requiring Unique Index在需要唯一索引的同时将多个文档插入 MongoDB
【发布时间】:2014-02-23 05:41:32
【问题描述】:

我的收藏Pphone 字段上有一个唯一索引:

db.P.ensureIndex( { phone: 1 }, { unique: true, dropDups: true } )
db.P.insert( {phone:"555-1234"} )

如果我插入一组文档,其中甚至一个文档都有重复键:

db.P.insert( [{phone:"911"},{phone:"555-1234"}] )
> E11000 duplicate key error index: test.P.$phone_1  dup key: { : "555-1234" }

整个插入失败,没有插入有效数字。

问题:如何进行批量插入,确保插入有效文档,并获取有关哪些插入失败的信息? 使用 nodejs api 显示代码的奖励积分。

【问题讨论】:

  • 我上次尝试时,这是不可能的。
  • 我相信您现在需要单独插入每个文档。

标签: node.js mongodb


【解决方案1】:

MongoDB 驱动程序有一个“ContinueOnError”选项,它会导致 mongo 跳过具有重复唯一键的记录。至于确定跳过的内容,根据文档:“如果在批量插入期间发生多个错误,客户端只会收到最后一个生成的错误。(http://docs.mongodb.org/manual/core/bulk-inserts/)。

对于 Node.js,它会类似于

db.P.insert( [{phone:"911"},{phone:"555-1234"}], {continueOnError:true} )

http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#insert

【讨论】:

  • 我找到了这个文档,但令人困惑的是,它在 mongo shell 上工作,但 在 nodejs 上工作。谢谢!
猜你喜欢
  • 2017-08-16
  • 2016-03-15
  • 1970-01-01
  • 2016-12-15
  • 2015-08-16
  • 1970-01-01
  • 1970-01-01
  • 2016-01-18
  • 1970-01-01
相关资源
最近更新 更多