简体   繁体   English

一次更新MongoDB中的多个文档

[英]Update multiple documents in MongoDB at once

Currently I work with MongoDB 4.0.目前我使用 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 ?问题是当我想将第一个项目的库存更新为 5 并将第二个项目的库存更新为 10 时,我可以像在insertMany那样一次更新多个文档吗? If yes, how to do that?如果是,如何做到这一点?

You should try the bulkWrite operation in mongodb您应该尝试在 mongodb 中执行bulkWrite操作

try {
   db.books.bulkWrite(
      [

         { updateOne :
            {
               "filter" : { "_id" : 1 },
               "update" : { $set : { "stock " : 5} }
            }
         },
         { updateOne :
            {
               "filter" : { "_id" : 2 },
               "update" : { $set : { "stock " : 10} }
            }
         }
      ]
   );
}
catch (e) {
   print(e);
}

https://docs.mongodb.com/manual/core/bulk-write-operations/ https://docs.mongodb.com/manual/core/bulk-write-operations/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM