Currently I work with MongoDB 4.0. I can insert multiple documents at once like this:
db.books.insertMany([
{
"_id" : 1,
"item" : "TBD",
"stock" : 0,
"info" : { "publisher" : "1111", "pages" : 430 },
"tags" : [ "technology", "computer" ],
"ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "lmn", "rating" : 5 } ],
"reorder" : false
},
{
"_id" : 2,
"item" : "XYZ123",
"stock" : 15,
"info" : { "publisher" : "5555", "pages" : 150 },
"tags" : [ ],
"ratings" : [ { "by" : "xyz", "rating" : 5 } ],
"reorder" : false
}
]);
The problem is when I want to update stock of first item to 5 and stock of second item to 10, can I update multiple documents at once like in insertMany
? If yes, how to do that?
You should try the bulkWrite
operation in mongodb
try {
db.books.bulkWrite(
[
{ updateOne :
{
"filter" : { "_id" : 1 },
"update" : { $set : { "stock " : 5} }
}
},
{ updateOne :
{
"filter" : { "_id" : 2 },
"update" : { $set : { "stock " : 10} }
}
}
]
);
}
catch (e) {
print(e);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.