Node.js MongoDB Update

Updating documents in MongoDB allows you to modify existing records based on specified conditions. Node.js, with the mongodb driver, provides powerful methods to perform updates on documents.

 

Key Features of MongoDB Update

  1. Update One: Modifies the first document that matches the query.
  2. Update Many: Modifies all documents that match the query.
  3. Flexible Operators: Use operators like $set, $unset, and $inc for precise updates.

 

Step 1 Prerequisites

Ensure MongoDB is installed and running, and the mongodb package is installed in your project.

npm install mongodb

Step 2 Update One Document

Modify the first document that matches the specified query.

Example Code

const { MongoClient } = require('mongodb');

// Connection URL and Database Name
const url = 'mongodb://127.0.0.1:27017';
const dbName = 'mydatabase';

async function updateOneDocument() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection('users');

    // Update one document where age is 25
    const result = await collection.updateOne(
      { age: 25 },
      { $set: { name: 'Alice Updated' } }
    );
    console.log(`${result.modifiedCount} document(s) updated`);
  } finally {
    await client.close();
  }
}

updateOneDocument().catch(console.error);

Output:

1 document(s) updated

Step 3 Update Multiple Documents

Update all documents that match the specified filter.

Example Code

async function updateMultipleDocuments() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection('users');

    // Update all documents where age is greater than 25
    const result = await collection.updateMany(
      { age: { $gt: 25 } },
      { $set: { status: 'Active' } }
    );
    console.log(`${result.modifiedCount} document(s) updated`);
  } finally {
    await client.close();
  }
}

updateMultipleDocuments().catch(console.error);

Output:

2 document(s) updated

Step 4 Increment Field Value

Use the $inc operator to increase or decrease a numeric field.

Example Code

async function incrementField() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection('users');

    // Increment age by 1 for documents where name is 'Alice'
    const result = await collection.updateMany(
      { name: 'Alice' },
      { $inc: { age: 1 } }
    );
    console.log(`${result.modifiedCount} document(s) updated`);
  } finally {
    await client.close();
  }
}

incrementField().catch(console.error);

Output:

1 document(s) updated

Step 5 Unset a Field

Remove a field from documents using the $unset operator.

Example Code

async function unsetField() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection('users');

    // Remove the 'status' field where age is greater than 25
    const result = await collection.updateMany(
      { age: { $gt: 25 } },
      { $unset: { status: '' } }
    );
    console.log(`${result.modifiedCount} document(s) updated`);
  } finally {
    await client.close();
  }
}

unsetField().catch(console.error);

Output:

2 document(s) updated

Step 6 Replace a Document

Replace an entire document using replaceOne.

Example Code

async function replaceDocument() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection('users');

    // Replace the document where name is 'Alice'
    const result = await collection.replaceOne(
      { name: 'Alice' },
      { name: 'Alice Replaced', age: 30, status: 'Replaced' }
    );
    console.log(`${result.modifiedCount} document(s) replaced`);
  } finally {
    await client.close();
  }
}

replaceDocument().catch(console.error);

Output:

1 document(s) replaced

 

Summary

MongoDB's update operations in Node.js are versatile, allowing you to modify documents with fine-grained control. You can update specific fields, increment values, remove fields, or replace entire documents. Always test updates carefully to ensure data integrity and desired outcomes.