nodejs mongoose bulk update

前端 未结 3 809
广开言路
广开言路 2021-02-06 06:02

I\'ve a collection of data and I need to add for every documents a new field. If I run a query to get all documents and the update every single one node.js is stopped, may be fo

相关标签:
3条回答
  • 2021-02-06 06:38

    You can drop down to the collection level and do a bulk update. This action will not be atomic - some of the writes can fail and others might succeed - but it will allow you to make these writes in a single round trip to your database.

    It looks like this:

    var bulk = People.collection.initializeUnorderedBulkOp();
    bulk.find({<query>}).update({<update>});
    bulk.find({<query2>}).update({<update2>});
    ...
    bulk.execute(function(err) {
        ...
    });
    

    Check out the docs here: http://docs.mongodb.org/manual/core/bulk-write-operations/

    0 讨论(0)
  • 2021-02-06 06:43

    This example should include all the cases that we can mix together using directly with Mongoose bulkWrite() function:

    Character.bulkWrite([
      {
        insertOne: {
          document: {
            name: 'Eddard Stark',
            title: 'Warden of the North'
          }
        }
      },
      {
        updateOne: {
          filter: { name: 'Eddard Stark' },
          // If you were using the MongoDB driver directly, you'd need to do
          // `update: { $set: { title: ... } }` but mongoose adds $set for
          // you.
          update: { title: 'Hand of the King' }
        }
      },
      {
        deleteOne: {
          {
            filter: { name: 'Eddard Stark' }
          }
        }
      }
    ]).then(res => {
     // Prints "1 1 1"
     console.log(res.insertedCount, res.modifiedCount, res.deletedCount);
    });
    

    Official Documentation: https://mongoosejs.com/docs/api.html#model_Model.bulkWrite

    0 讨论(0)
  • 2021-02-06 06:54

    More detailed info about the query and update query.

    var bulk = People.collection.initializeOrderedBulkOp();
        bulk.find(query).update(update);
        bulk.execute(function (error) {
           callback();                   
        });
    

    Query is searching with array.
    Update needs a $set

    var bulk = People.collection.initializeOrderedBulkOp();
        bulk.find({'_id': {$in: []}}).update({$set: {status: 'active'}});
        bulk.execute(function (error) {
             callback();                   
        });
    

    Query is a searching the id

    var bulk = People.collection.initializeOrderedBulkOp();
        bulk.find({'_id': id}).update({$set: {status: 'inactive'}});
        bulk.execute(function (error) {
             callback();                   
        });
    
    0 讨论(0)
提交回复
热议问题