Open In App

Mongoose Document Model.bulkWrite() API

Improve
Improve
Like Article
Like
Save
Share
Report

The Model.bulkWrite() method of the Mongoose API is used to perform multiple operations in one command. It can insert multiple documents, can update one or multiple documents, can replace documents, can delete documents in one single command. This is faster in performance than multiple independent create commands.

Syntax:

Model.bulkWrite()

Parameters: The Model.bulkWrite() method accepts three parameters:

  • operations:  It is an array of objects with various operations. Like: insertOne, updateOne, updateMany, deleteOne, deleteMany, replaceOne etc.
  • options: It is an object with various properties.
  • callback: It is a callback function that will run once execution is completed.

Return Value: The Model.bulkWrite() function returns a promise. Named as BulkWriteOpResult if command succeeds.

Setting up Node.js application:

Step 1: Create a Node.js application using the following command:

npm init

Step 2: After creating the NodeJS application, Install the required module using the following command:

npm install mongoose

Project Structure: The project structure will look like this:

 

Database Structure: The database structure will look like this, the following documents are present in the collection.

 

Example 1: In this example, We have established a database connection using mongoose and defined model over userSchema, having two columns or fields “name” and “age”. At the end, we are using bulkWrite() method on the User model which is having various operations like insertOne, UpdateOne. We are providing these as an array of objects as the first parameter to bulkWrite() method. In this example, we have inserted one new document and updated the existing document.

  • app.js: Write down the below code in the app.js file:

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const userSchema = new mongoose.Schema({
    name: String,
    age: Number,
});
  
// Defining userSchema model
const User = mongoose.model("User", userSchema);
User.bulkWrite([
    {
        insertOne: {
            document: {
                name: "User4",
                age: 30,
            },
        },
    },
    {
        updateOne: {
            filter: { name: "User1" },
            update: { name: "User1 Updated" },
        },
    },
]).then((result) => {
    console.log(result);
});


Steps to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

BulkWriteResult {
  result: {
    ok: 1,
    writeErrors: [],
    writeConcernErrors: [],   
    insertedIds: [ [Object] ],
    nInserted: 1,
    nUpserted: 0,
    nMatched: 1,
    nModified: 1,
    nRemoved: 0,
    upserted: []
  }
}

GUI Representation of the  Database using Robo3T GUI tool:

 

Example 2: In this example, we are performing deleteOne and deleteMany operation using bulkWrite() method. Below is the documents present in collection before executing the command.

 

  • app.js: Write down the below code in the app.js file:

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
const userSchema = new mongoose.Schema({
    name: String,
    age: Number,
});
  
// Defining userSchema model
const User = mongoose.model("User", userSchema);
  
User.bulkWrite([
    {
        deleteOne: {
            filter: { name: "User4" }
        }
    },
    {
        deleteMany: {
            filter: { age: 20 },
        }
    },
]).then((result) => {
    console.log(result);
});


Steps to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

BulkWriteResult {
  result: {
    ok: 1,
    writeErrors: [],       
    writeConcernErrors: [],
    insertedIds: [],       
    nInserted: 0,
    nUpserted: 0,
    nMatched: 0,
    nModified: 0,
    nRemoved: 3,
    upserted: []
  }
}

GUI Representation of the  Database using Robo3T GUI tool:

 

Reference: https://mongoosejs.com/docs/api/model.html#model_Model-bulkWrite



Last Updated : 19 Sep, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads