Careeroza
arrayFilters
Targeted updates
$push → adds a value to an array
Example: db.users.updateOne({ name: "Rahul" }, { $push: { hobbies: "cricket" } })
$push with $each → adds multiple values
db.users.updateOne({ name: "Rahul" }, { $push: { hobbies: { $each: ["music", "reading"] } } })
$addToSet → adds only if value is not already present (no duplicates)
db.users.updateOne({ name: "Rahul" }, { $addToSet: { hobbies: "cricket" } })
$pull → removes a specific value from array
db.users.updateOne({ name: "Rahul" }, { $pull: { hobbies: "cricket" } })
$pop → removes first or last element
1 → last element, -1 → first element
db.users.updateOne({ name: "Rahul" }, { $pop: { hobbies: 1 } })
$set (for arrays) → updates value at specific index
db.users.updateOne({ name: "Rahul" }, { $set: { "hobbies.0": "football" } })
$ (positional operator) → updates matched element
db.users.updateOne({ hobbies: "cricket" }, { $set: { "hobbies.$": "football" } })
$[] → updates all elements in array
db.users.updateOne({}, { $set: { "scores.$[]": 100 } })
$[identifier] → updates elements based on condition
db.users.updateOne({}, { $set: { "scores.$[e]": 100 } }, { arrayFilters: [{ "e": { $lt: 50 } }] })
Simple understanding:
$push → add
$addToSet → add without duplicates
$pull → remove
$pop → remove first/last
$set → update
$ / $[] / $[ ] → target specific elements