MongoDB
Update & Delete
Modify and remove documents with update operators.
By EZ4Code Team
updatedeletecrud
Code
// Update operators
db.users.updateOne(
{ _id: ObjectId("...") },
{ $set: { lastLogin: new Date() },
$inc: { loginCount: 1 },
$push: { logins: new Date() } }
);
// Update many documents
db.products.updateMany(
{ category: "books" },
{ $mul: { price: 0.9 } } // 10% discount
);
// Upsert
db.users.updateOne(
{ email: "[email protected]" },
{ $setOnInsert: { createdAt: new Date() },
$set: { name: "Alice" } },
{ upsert: true }
);
// Delete
db.users.deleteOne({ _id: ObjectId("...") });
db.users.deleteMany({ inactive: true });Explanation
Update operators like $set, $inc, and $push modify fields atomically without replacing the whole document. $setOnInsert only applies during an upsert insert, useful for immutable createdAt. deleteOne/deleteMany remove matching documents; deleted data cannot be recovered without a backup.
More MongoDB Snippets
Insert & Find
Insert documents and query a collection.
Query Operators
Use comparison, logical, array, and regex operators.
Aggregation Pipeline
Build multi-stage pipelines for analytics.
Indexes
Create single, compound, and text indexes for performance.
Collections & Schema
Manage collections, validators, and capped collections.
Replica Set
Configure a replica set for high availability.