Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb multi document insert ignore custom duplicate field error

I have to insert 3 recordset from array 1 already exists and 2 are new

e.g:

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

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

as for now none of them are getting inserted and throwing err: 'E11000 duplicate key error index: mongotest.mothership.$imagename_1 dup

any suggestion how to insert remaining two ignoring error in single go !

like image 883
Rizwan Patel Avatar asked Jun 06 '26 08:06

Rizwan Patel


1 Answers

Unordered insert will do the trick

db.products.insert(
    [{ imagename: "pen1", qty: 21 },
     { imagename: "pen", qty: 20 },
     { imagename: "eraser", qty: 25 }],
    { ordered: false }
)
like image 181
somallg Avatar answered Jun 08 '26 00:06

somallg