Mongodb multilingual insertion ignores custom repeating field error

I need to insert 3 recordsets from array 1 already exists, and 2 - new

eg:

db.products.insert(
   [
     { imagename: "pen1", qty: 21 },
     { imagename: "pen", qty: 20 },
     { imagename: "eraser", qty: 25 }
   ]
)

Where "{imagename:" pen ", qty: 20}" `already exists and has a unique key on the" imagename "field in mongodb

since now none of them gets up and throws err: "E11000 duplicates the key error index: mongotest.mothership. $ imagename_1 dup

any suggestion on how to insert the remaining two ignore errors into one go!

+4
source share
3 answers

(https://docs.mongodb.org/v3.0/reference/method/db.collection.insert/#perform-an-unordered-insert)

db.products.insert(
    [{ imagename: "pen1", qty: 21 },
     { imagename: "pen", qty: 20 },
     { imagename: "eraser", qty: 25 }],
    { ordered: false }
)
+7

: securityIndex v.0.0.0 https://docs.mongodb.com/manual/reference/method/db.collection.ensureIndex/

as-is ( ensure create - ), db.products.ensureIndex db.products.createIndex.


. :

db.products.ensureIndex({ url: 1 }, { unique: true, background: true, dropDups: true })

db.products.insert(
    [{ imagename: "pen", qty: 21 },
     { imagename: "pen", qty: 20 },
     { imagename: "eraser", qty: 25 }],
    { ordered: false }
)

: E11000 : mongotest.products: imagename_1 dup key: {: 'pen'}. . ... catche

try {
db.products.insert(
        [{ imagename: "pen", qty: 21 },
         { imagename: "pen", qty: 20 },
         { imagename: "eraser", qty: 25 }],
        { ordered: false }
    )
}catch(e){
print(e)
}

: secureIndex, insert.because. makeIndex , securityIndex .

0

ordered false. , . , .

const documents = [{name: "Star Wars"}, {name: "Sword Art Online"}];
db.product.insertMany(documents, {ordered: false});

Mongoose, Model.insertMany().


. , , MongoDB .


BulkWriteError.

Write Concern, , .


db.collection.insertMany()

.

db.collection.insertMany(
   [ <document 1> , <document 2>, ... ],
   {
      writeConcern: <document>,
      ordered: <boolean>
   }
)

ordered: . , , mongod . true.

0

Source: https://habr.com/ru/post/1619012/


All Articles