await testCollection.insertMany(testArray, { ordered: false });
我有这个密码。我发现放入{ ordered: false }将防止得到E11000错误代码。但是,看起来,它并没有。有什么方法可以避免这个错误吗?我想跳过并且不插入具有相同_id代码的文档。
{ ordered: false }
E11000
jv4diomz1#
您无法避免错误,但可以继续插入。请看这里。例如:
MongoDB Enterprise replset:PRIMARY> db.products.insert( ... [ ... { _id: 20, item: "lamp", qty: 50, type: "desk" }, ... { _id: 21, item: "lamp", qty: 20, type: "floor" }, ... { _id: 21, item: "lamp", qty: 20, type: "floor" }, ... { _id: 22, item: "bulk", qty: 100 } ... ], ... { ordered: false } ... ) BulkWriteResult({ "writeErrors" : [ { "index" : 2, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: newdb1.products index: _id_ dup key: { _id: 21.0 }", "op" : { "_id" : 21, "item" : "lamp", "qty" : 20, "type" : "floor" } } ], "writeConcernErrors" : [ ], "nInserted" : 3, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) MongoDB Enterprise replset:PRIMARY> db.products.find() { "_id" : 20, "item" : "lamp", "qty" : 50, "type" : "desk" } { "_id" : 21, "item" : "lamp", "qty" : 20, "type" : "floor" } { "_id" : 22, "item" : "bulk", "qty" : 100 }
你可能会看到,如果你删除{ ordered: false },唯一插入的记录将是第一个错误发生之前的记录:
MongoDB Enterprise replset:PRIMARY> db.products.find() { "_id" : 20, "item" : "lamp", "qty" : 50, "type" : "desk" } { "_id" : 21, "item" : "lamp", "qty" : 20, "type" : "floor" }
1条答案
按热度按时间jv4diomz1#
您无法避免错误,但可以继续插入。请看这里。例如:
你可能会看到,如果你删除
{ ordered: false }
,唯一插入的记录将是第一个错误发生之前的记录: