MongoDB Update Tutorial

The MongoDB Update operation is used to modify the existing documents in a collection using the two methods updateOne and updateMany methods.

Update a Single Document

The updateOne() to modify a single document that matches a specific filter.

db.myCollection.updateOne({ name: "John" }, { $set: { age: 31 } });
        

Update Multiple Documents

The updateMany() to modify multiple documents that match a specific filter.

db.myCollection.updateMany({ age: { $lt: 25 } }, { $set: { status: "Young" } });
        

Update or Insert with upsert

With upsert set to true, updateOne will insert a document if no matching document is

db.myCollection.updateOne({ name: "Alice" }, { $set: { age: 26 } }, { upsert: true });
        

Result of Update Operations

The updateOne() and updateMany() return a result object with information about the

const result = db.myCollection.updateOne({ name: "John" }, { $set: { age: 31 } });
printjson(result);
          

Updating Nested Documents

To modify fields within nested documents, use dot notation.

db.myCollection.updateOne({ "address.city": "New York" }, { $set: { "address.zipCode": "10001" } });
        

Updating Arrays

The operators like $push, $pull, and $addToSet to modify arrays in documents.

db.myCollection.updateOne({ name: "Alice" }, { $push: { hobbies: "Swimming" } });
        

Increment or Decrement Fields

Using$inc operator we increment or decrement numeric fields.

db.myCollection.updateOne({ name: "John" }, { $inc: { age: 1 } });
        

Removing Fields

The $unset to remove specific fields from a document.

db.myCollection.updateOne({ name: "John" }, { $unset: { age: 1 } });