Node.js MongoDB: Update Documents

Welcome to The Coding College! In this tutorial, we’ll learn how to update documents in a MongoDB collection using Node.js. Updating documents is essential for modifying existing data based on changing requirements or correcting errors.


Prerequisites

Before proceeding, ensure you have the following:

  1. Node.js Installed: Download Node.js.
  2. MongoDB Installed: Install MongoDB.
  3. MongoDB Node.js Driver Installed: Run: npm install mongodb

Step 1: Connect to MongoDB

First, establish a connection to MongoDB. Create a file named updateData.js and include this code:

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

// MongoDB connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

// Database and Collection Names
const dbName = 'myNewDatabase';
const collectionName = 'users';

async function connectToDatabase() {
  try {
    await client.connect();
    console.log('Connected to MongoDB.');
    return client.db(dbName).collection(collectionName);
  } catch (err) {
    console.error('Database connection error:', err.message);
  }
}

Step 2: Update a Single Document

To update a single document, use the updateOne() method.

Example: Updating the Name of a User

async function updateOneDocument() {
  const collection = await connectToDatabase();

  const filter = { name: 'John Doe' }; // Find the document
  const update = { $set: { name: 'John Smith', age: 30 } }; // Changes to apply

  const result = await collection.updateOne(filter, update);
  console.log(`${result.modifiedCount} document(s) updated.`);
}

updateOneDocument();

Step 3: Update Multiple Documents

To update multiple documents at once, use the updateMany() method.

Example: Incrementing the Age of All Users by 1

async function updateManyDocuments() {
  const collection = await connectToDatabase();

  const filter = { age: { $gte: 18 } }; // Find users aged 18 or older
  const update = { $inc: { age: 1 } }; // Increment age by 1

  const result = await collection.updateMany(filter, update);
  console.log(`${result.modifiedCount} document(s) updated.`);
}

updateManyDocuments();

Step 4: Replace an Entire Document

Use the replaceOne() method to completely replace a document with a new one.

Example: Replace a User Document

async function replaceDocument() {
  const collection = await connectToDatabase();

  const filter = { name: 'Alice' };
  const newDocument = { name: 'Alice Johnson', age: 25, city: 'New York' };

  const result = await collection.replaceOne(filter, newDocument);
  console.log(`${result.modifiedCount} document(s) replaced.`);
}

replaceDocument();

Step 5: Upsert (Update or Insert)

The upsert option creates a new document if no matching document is found.

Example: Upserting a Document

async function upsertDocument() {
  const collection = await connectToDatabase();

  const filter = { name: 'Bob' };
  const update = { $set: { name: 'Bob', city: 'San Francisco' } };

  const options = { upsert: true }; // Enable upsert
  const result = await collection.updateOne(filter, update, options);

  console.log(result.upsertedCount > 0 ? 'Document inserted.' : 'Document updated.');
}

upsertDocument();

Example Outputs

  1. Updating a Single Document: Connected to MongoDB. 1 document(s) updated.
  2. Updating Multiple Documents: Connected to MongoDB. 5 document(s) updated.
  3. Upserting a Document: Connected to MongoDB. Document inserted.

Best Practices

  1. Use Specific Filters: Always use precise filters to avoid updating unintended documents.
  2. Test Before Updating: Test your filter conditions using find() to ensure accuracy.
  3. Backup Data: Maintain a backup, especially for critical data.
  4. Atomic Updates: Use MongoDB’s atomic update operators ($set, $inc, $unset, etc.) for efficiency.
  5. Validation: Validate updated data to ensure it complies with your application’s schema.

Conclusion

Updating MongoDB documents with Node.js is powerful and flexible. The updateOne(), updateMany(), and replaceOne() methods, combined with MongoDB’s atomic operators, offer a wide range of options for managing your data efficiently.

For more tutorials and coding resources, visit The Coding College.

Happy coding! 🚀

Leave a Comment