【问题标题】:Bulk Save/Update lists of data in MongoDB (Nodejs)在 MongoDB (Nodejs) 中批量保存/更新数据列表
【发布时间】:2019-12-18 19:13:46
【问题描述】:

我有要保存的数据列表,如果已经存在,请更新。 我可以使用循环来做到这一点。但是有没有像insertMany这样的其他方式,它只支持插入,但我也想批量插入和更新。

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query


    【解决方案1】:

    您可以使用 Mongo 驱动程序提供的批量更新功能。您可以将它们添加到批量事务中并作为批处理执行,而不是在循环中调用事务。

    首先需要初始化批量操作,有序/无序:

    var bulk = db.collection.initializeUnorderedBulkOp();
    

    var bulk = db.collection.initializeOrderedBulkOp();
    

    然后您可以继续向批量对象添加事务。

    bulk.insert( { 
        // attributes 
    } );    // insert operation
    

    bulk.find( { 
        // query attributes
    } ).update( { 
        $set: { 
            // set attributes
    } } ); // update operation
    

    最后你需要调用

    bulk.execute();
    

    我不知道这是否能达到你的目的。

    请参考此链接:

    https://docs.mongodb.com/manual/reference/method/Bulk/

    【讨论】:

      【解决方案2】:

      将 updateMany 与选项 { upsert: true } 一起使用,如果文档已存在则更新文档,否则插入新文档。

      找到下面的餐厅收藏示例

      { "_id" : 1, "name" : "Central Perk Cafe", "violations" : 3 }
      { "_id" : 2, "name" : "Rock A Feller Bar and Grill", "violations" : 2 }
      { "_id" : 3, "name" : "Empire State Sub", "violations" : 5 }
      { "_id" : 4, "name" : "Pizza Rat's Pizzaria", "violations" : 8 }
      

      下面的查询更新违规等于 4 的文档,如果文档不存在则插入新文档。

      db.restaurant.updateMany(
        { violations: 4 },
        { $set: { "name" : "Eat and Treat" } },
        { upsert: true }
      );
      

      在此处查找更多详细信息:

      https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/

      【讨论】:

        猜你喜欢
        • 2021-03-21
        • 2017-05-13
        • 1970-01-01
        • 1970-01-01
        • 2011-05-25
        • 1970-01-01
        • 2015-02-10
        • 2016-02-26
        • 1970-01-01
        相关资源
        最近更新 更多