我的收藏集P
在phone
字段中有唯一索引:
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显示代码的加分点。
答案 0 :(得分:2)
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