Loading

Quipoin Menu

Learn • Practice • Grow

mongodb / Update Operations
interview

Q1. How do you update a single document?
Use updateOne() to modify the first document matching the filter:
db.users.updateOne(
  { name: "John" },
  { $set: { age: 31, city: "Boston" } }
)
The $set operator updates specified fields. Other operators include $unset, $inc, $push, etc.

Q2. How do you update multiple documents?
Use updateMany() to modify all documents matching the filter:
db.users.updateMany(
  { age: { $lt: 18 } },
  { $set: { status: "minor" } }
)
Be careful with updateMany as it can affect many documents.

Q3. What is the $inc operator?
$inc increments a numeric field by a specified value:
db.products.updateOne(
  { name: "Laptop" },
  { $inc: { stock: -1, sold: 1 } }
)
It creates the field if it doesn't exist (starting from 0).

Q4. How do you update array fields?
Use array operators like $push, $pull, $addToSet:
db.users.updateOne(
  { name: "John" },
  { $push: { hobbies: "reading" } }
)

db.users.updateOne(
  { name: "John" },
  { $pull: { hobbies: "swimming" } }
)

Q5. What is upsert in update operations?
Upsert (update + insert) creates a new document if no document matches the filter. Set the upsert option to true:
db.users.updateOne(
  { email: "new@example.com" },
  { $set: { name: "New User" } },
  { upsert: true }
)
This is useful for ensuring a document exists.