Bulk Actions

Lesson 8
Author : Afrixi
Last Updated : February, 2023
MongoDB - noSQL Database
This course covers the basics of working with MongoDB.

Bulk actions in MongoDB refer to performing multiple operations on a collection of documents in a single request. This can be achieved using the bulkWrite() method provided by the MongoDB driver.

Here is an example of using bulkWrite() to insert multiple documents into a collection:

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });

client.connect(err => {
  const collection = client.db("test").collection("users");
  
  const documents = [
    { name: "John", age: 30 },
    { name: "Jane", age: 25 },
    { name: "Bob", age: 35 }
  ];

  collection.bulkWrite(documents.map(doc => ({
    insertOne: {
      document: doc
    }
  })), (err, result) => {
    console.log(result);
    client.close();
  });
});

In this example, we first create an array of documents that we want to insert into the “users” collection. We then use bulkWrite() to generate a list of write operations for each document, in this case, insertOne. Finally, we call bulkWrite() with the list of operations to execute them.

You can also use bulkWrite() to perform update and delete operations on documents. Here is an example of updating multiple documents in a collection:

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });

client.connect(err => {
  const collection = client.db("test").collection("users");
  
  const filter = { age: { $lt: 30 } };
  const update = { $set: { age: 30 } };
  
  collection.bulkWrite([
    {
      updateMany: {
        filter,
        update
      }
    }
  ], (err, result) => {
    console.log(result);
    client.close();
  });
});

In this example, we are updating all documents in the “users” collection where the age field is less than 30. We first define the filter and the update operation that we want to apply. We then use bulkWrite() to generate an updateMany operation with the filter and update, and pass it to the bulkWrite() method to execute it.

Similarly, you can use bulkWrite() to perform delete operations on multiple documents in a collection by using the deleteMany operation.