Skip to content
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