Beginner LevelMongoDB & Mongoose
How do MongoDB update operators ($set, $unset, $inc, $push, $pull) modify documents?
❓ Interview Prompt: Explain atomic update operators ($set, $unset, $inc, $mul, $push, $pull, $addToSet) and avoiding full-document replacements.
Update operators modify specific document fields in-place on the database server without reading or re-transmitting full documents:
•
'$set': Replaces field value.
•
'$unset': Deletes field from document.
•
'$inc': Increments/decrements numeric value atomically.
•
'$push': Appends item to array.
•
'$addToSet': Appends item to array ONLY if it does not already exist (prevents duplicates!).
Code Implementation Example
typescript
import { UserModel } from './models/User';
async function updateUserStats(userId: string, pointsEarned: number, newTag: string) {
await UserModel.updateOne(
{ _id: userId },
{
$inc: { loginCount: 1, rewardPoints: pointsEarned },
$addToSet: { tags: newTag },
$set: { lastActive: new Date() }
}
);
}💡Executing in-place document updates using $inc, $addToSet, and $set.
🎯 Interview Key Takeaway
Always use update operators ($set, $inc, $addToSet) rather than overwriting full documents to avoid race condition write bugs.
#Update Operators#$set#$inc#$addToSet#Beginner
Back to all MongoDB & Mongoose Questions→