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
| Operator | Description |
|---|---|
| $set | Set field value |
| $unset | Remove field |
| $inc | Increment value |
| $push | Add to array |
| $pull | Remove from array |
| $rename | Rename 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
- Update single document
- Update multiple documents
- Use upsert
- 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.