MongoDB
Beginner
1 min read
Update Operations
Example
// $set — update specific fields only
await db.collection('users').updateOne(
{ email: "carol@example.com" },
{ $set: { age: 29, updatedAt: new Date() } }
)
// $inc — increment a counter atomically
await db.collection('products').updateOne(
{ name: "Keyboard" },
{ $inc: { stock: -1, soldCount: 1 } }
)
// $push — append to an array
await db.collection('users').updateOne(
{ email: "carol@example.com" },
{ $push: { hobbies: "photography" } }
)
// $pull — remove a value from an array
await db.collection('users').updateOne(
{ email: "carol@example.com" },
{ $pull: { hobbies: "cycling" } }
)
// updateMany — update all matching documents
await db.collection('products').updateMany(
{ stock: { $lt: 10 } },
{ $set: { lowStock: true } }
)
// upsert — insert if not found
await db.collection('sessions').updateOne(
{ sessionId: "abc123" },
{ $set: { userId: "u1", lastSeen: new Date() } },
{ upsert: true }
)