nodejs mongoose bulk update

前端 未结 3 817
广开言路
广开言路 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: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

提交回复
热议问题