</>
Skip to content
MongoDB lessons (12/38)

MongoDB — Update

Update One

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

Update Many

db.users.updateMany(
  { active: true },
  { $set: { lastLogin: new Date() } }
)

Update Operators

OperatorDescription
$setSet field value
$unsetRemove field
$incIncrement value
$pushAdd to array
$pullRemove from array
$renameRename field

Examples

// Increment
db.users.updateOne({ name: "John" }, { $inc: { age: 1 } })

// Add to array
db.users.updateOne({ name: "John" }, { $push: { hobbies: "new" } })

// Remove from array
db.users.updateOne({ name: "John" }, { $pull: { hobbies: "old" } })

// Rename field
db.users.updateOne({ name: "John" }, { $rename: { "name": "fullName" } })

Upsert

db.users.updateOne(
  { name: "New User" },
  { $set: { email: "new@example.com" } },
  { upsert: true }
)

Replace

db.users.replaceOne(
  { name: "John" },
  { name: "John Doe", email: "new@example.com" }
)

Mini Practice

  1. Update single document
  2. Update multiple documents
  3. Use upsert
  4. Use different update operators

Up Next

Continue with Delete — deleting documents.

Related Topics

Frequently Asked Questions about Update

What is Update in MongoDB?

Update is a fundamental concept in MongoDB. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Update?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Update.

Why is Update important in MongoDB?

Update is essential for MongoDB development. Understanding this concept will help you write better code and solve real-world problems more effectively.