MongoDB Update

MongoDB Update Documents: Full Guide

Updating documents in MongoDB is a crucial operation that allows you to modify existing data in your collections. MongoDB provides several update methods like updateOne, updateMany and findOneAndUpdate for precise and bulk updates. This guide explains how to use these methods efficiently with practical examples in the shell, Node.js, and Compass.

Why Update Documents in MongoDB?

  1. Modify Existing Data: Update fields or values in specific documents.
  2. Bulk Updates: Modify multiple documents at once with ease.
  3. Flexible Operators: MongoDB provides various update operators like $set, $unset and $inc for detailed modifications.

Key Features of MongoDB Update

  • Precise Updates: Use filters to target specific documents.
  • Bulk Updates: Apply changes to multiple documents simultaneously.
  • Advanced Operators: MongoDB supports a variety of operators for different update scenarios.

Prerequisites

  1. MongoDB Installed: Download MongoDB from mongodb.com.
  2. Node.js Installed: Download and install Node.js from nodejs.org.
  3. MongoDB Shell or Compass Installed: Use either for database management.

Update Methods in MongoDB

  1. updateOne: Updates the first document that matches the condition.
  2. updateMany: Updates all documents that match the condition.
  3. findOneAndUpdate: Updates a document and returns the updated document.

Method 1: Update Documents Using MongoDB Shell

Step 1: Open the MongoDB Shell

Run the following command:

mongosh

Step 2: Switch to a Database

Select the database you want to use:

use myDatabase

Step 3: Update a Single Document

Use updateOne to modify the first matching document:

db.users.updateOne(
{ name: 'Alice' },
{ $set: { age: 26 } }
);

Explanation:

  • Filter: { name: ‘Alice’ } finds the document where name is Alice.
  • Update Operator: $set modifies the age field to 26.

Step 4: Update Multiple Documents

Use updateMany to modify all matching documents:

db.users.updateMany(
{ city: 'New York' },
{ $set: { isActive: true } }
);

Step 5: Remove a Field

Use $unset to remove a field from a document:

db.users.updateOne(
{ name: 'Alice' },
{ $unset: { isActive: '' } }
);

Method 2: Update Documents Using Node.js

Step 1: Install MongoDB Driver

Run the following command to install the MongoDB driver:

npm install mongodb

Step 2: Perform Update Operations in Node.js

Create a file named app.js and write the following code:

Update a Single Document
const { MongoClient } = require('mongodb');

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

// Database Name
const dbName = 'myDatabase';

async function updateOneDocument() {
try {
await client.connect();
console.log('Connected successfully to MongoDB');

const db = client.db(dbName);
const collection = db.collection('users');

// Update a single document
const result = await collection.updateOne(
{ name: 'Alice' },
{ $set: { age: 26 } }
);
console.log('Matched documents:', result.matchedCount);
console.log('Modified documents:', result.modifiedCount);
} catch (err) {
console.error('Error updating document:', err);
} finally {
await client.close();
}
}

updateOneDocument();
Update Multiple Documents
async function updateManyDocuments() {
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');

// Update multiple documents
const result = await collection.updateMany(
{ city: 'New York' },
{ $set: { isActive: true } }
);
console.log('Matched documents:', result.matchedCount);
console.log('Modified documents:', result.modifiedCount);
} catch (err) {
console.error('Error updating documents:', err);
} finally {
await client.close();
}
}

updateManyDocuments();
Use findOneAndUpdate
async function findOneAndUpdateDocument() {
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');

// Find and update a document
const result = await collection.findOneAndUpdate(
{ name: 'Alice' },
{ $set: { age: 27 } },
{ returnDocument: 'after' } // Return the updated document
);
console.log('Updated document:', result.value);
} catch (err) {
console.error('Error updating document:', err);
} finally {
await client.close();
}
}

findOneAndUpdateDocument();

Method 3: Update Documents Using MongoDB Compass

MongoDB Compass provides a GUI for managing updates.

Step 1: Open MongoDB Compass

  1. Launch MongoDB Compass and connect to your MongoDB server (mongodb://localhost:27017).
  2. Select your database and collection.

Step 2: Update a Document

  1. Filter the document you want to update using the query box, e.g., { name: ‘Alice’ }.
  2. Click “Update Document” and modify the fields.
  3. Save the changes to update the document.

Advanced Update Operations

1. Increment a Field

Use $inc to increase or decrease a numeric value:

const result = await collection.updateOne(
{ name: 'Alice' },
{ $inc: { age: 1 } }
);
console.log('Age incremented:', result.modifiedCount);

2. Add Elements to an Array

Use $push to add an element to an array field:

const result = await collection.updateOne(
{ name: 'Alice' },
{ $push: { hobbies: 'Reading' } }
);

3. Update Only If the Field Exists

Use $set with $exists to conditionally update:

const result = await collection.updateOne(
{ name: 'Alice', isActive: { $exists: true } },
{ $set: { age: 30 } }
);

Real-World Use Case

Imagine you’re managing a subscription service and want to update the subscription status of all users who haven’t renewed for the past year.

Example: Updating Subscription Status

async function updateSubscriptions() {
const db = client.db('subscriptions');
const collection = db.collection('users');

const result = await collection.updateMany(
{ lastRenewed: { $lt: new Date(new Date().setFullYear(new Date().getFullYear() - 1)) } },
{ $set: { status: 'inactive' } }
);
console.log('Updated inactive subscriptions:', result.modifiedCount);
}

updateSubscriptions();

Leave a Comment

BoxofLearn