How to update documents in MongoDB

Photo by Rubaitul Azad on Unsplash

Whether you’re updating a single document or multiple documents, MongoDB has you covered with methods like updateOne(), updateMany(), and various update operators.

Using updateOne() and updateMany()

These methods are used to update one or multiple documents in a collection, and their usage is pretty straightforward.

Basic Syntax

Here’s the basic syntax for both methods:

db.collection('collectionName').updateOne(filter, update, options);
db.collection('collectionName').updateMany(filter, update, options);
  • filter: The conditions for finding the document(s) to update.
  • update: Describes the modifications to be made.
  • options: Additional options like upsert.

Example: Updating Age for a Single Student

db.collection('students').updateOne(
{ name: "John" },
{ $set: { age: 22 } }
);

Example: Updating Age for Multiple Students

db.collection('students').updateMany(
{ age: { $lt: 20 } },
{ $set: { status: "underage" } }
);

Update Operators

MongoDB provides a rich set of update operators for different types of data manipulation.

Common Field Update Operators

  • $set: Sets the value of a field.
  • $inc: Increments a field’s value.
  • $min: Updates the field to the minimum value specified.

Working with Arrays

  • $., $[], and $[<identifier>] + arrayFilters: These shortcuts allow you to specify elements in an array to update.
  • $push and $pop: Add or remove elements in an array.

Example: Incrementing a Score in an Array

db.collection('students').updateOne(
{ name: "John" },
{ $inc: { "scores.0.score": 1 } }
);

Example: Adding an Element to an Array

db.collection('students').updateOne(
{ name: "John" },
{ $push: { hobbies: "Reading" } }
);

Replacing Documents with replaceOne()

Apart from updating specific fields in documents, MongoDB also allows you to replace an entire document using the replaceOne() method.

Example: Replacing a Document

db.collection('students').replaceOne(
{ name: "John" },
{ name: "John", age: 22, status: "active" }
);

This will replace the document where the name is “John” with the new document specified.

Summary

Updating documents in MongoDB can be as simple or as complex as you need it to be, thanks to the array of methods and operators available. Whether you’re performing a straightforward field update with updateOne() or tackling more complex manipulations with updateMany() and various operators, MongoDB has the flexibility to meet your needs.

,