More Update Operators: $inc, $push, $pull and $addToSet
$inc lets the database do the counting so no count is lost, $currentDate stamps when a change happened, $push and $pull add to and remove from a list, and $addToSet adds an item only when it isn't there yet.
Apprentice · MongoDB · Updated
After this lesson you can
- Count up or down with $inc and stamp a change with $currentDate, and explain why the database should do the counting
- Add to and remove from an array with $push, $addToSet and $pull, and predict when $push adds a duplicate
Key takeaways
- $inc adds a number to a field, or subtracts with a negative one. A missing field counts as 0.
- Counting in the database is safer than reading a number, adding to it in the app and writing it back, where two saves at once can lose one.
- $push adds an item to the end of an array, even when the same item is already there.
- $addToSet adds an item only when the array doesn't hold it yet, and $pull removes every item equal to the value.
- $currentDate sets a field to the date and time the update ran.
Likes on a post, views of a video, items in a shopping cart, songs in a playlist: some of the most common changes in an app add one to a number or add something to a list. $set can do them, but not safely, and not without extra work. You'll use the operators in this lesson whenever a number goes up or down or a list grows or shrinks.
The examples use Sunday Kitchen's 40 recipes from Adding Many Documents with insertMany. In mongosh, after use sunday_kitchen, load them again first:
load("sunday-kitchen-recipes.js")
true
Counting saves: who does the math?
Sunday Kitchen wants to count how many cooks save each recipe. The plain way: when a cook taps Save, the app reads the recipe's count, adds 1, and writes the new number back with $set. It works, until two cooks tap Save on Chickpea Curry at the same moment. Both apps read 3, both add 1, and both write 4. Two saves happened, and the count went up by one. That's called a lost update, and it happens whenever a number is read in one step and written in another.

$inc: let the database count
$inc (read "increment", which means "increase by") hands the arithmetic to the database. Chickpea Curry, _id 4, has no saves field yet, and $inc treats a missing field as 0:
db.recipes.updateOne({ _id: 4 }, { $inc: { saves: 1 } })
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
Two more cooks save it:
db.recipes.updateOne({ _id: 4 }, { $inc: { saves: 1 } })
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
db.recipes.updateOne({ _id: 4 }, { $inc: { saves: 1 } })
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
db.recipes.findOne({ _id: 4 }, { name: 1, saves: 1 })
{ _id: 4, name: 'Chickpea Curry', saves: 3 }
Each $inc is done whole, inside the database, before the next one starts, so two at the same moment add 2, never 1. A negative number counts down, as when a cook un-saves a recipe: { $inc: { saves: -1 } }.
One update can use several operators. $currentDate (read "current date") sets a field to the date and time the update runs, by the database's clock:
db.recipes.updateOne({ _id: 4 }, { $inc: { saves: 1 }, $currentDate: { lastSaved: true } })
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
db.recipes.countDocuments({ lastSaved: { $type: "date" } })
1
Chickpea Curry now has 4 saves and a lastSaved date: the moment you ran it.
Lists: $push and $pull
Each Sunday Kitchen cook keeps a list of favorite recipes. Add three cooks in a new cooks collection (if you've run this before, run db.cooks.drop() first):
db.cooks.insertMany([
{ _id: 1, name: "Maya", favorites: ["Chickpea Curry", "Black Bean Tacos"] },
{ _id: 2, name: "Leo", favorites: ["Lemon Bars"] },
{ _id: 3, name: "Priya", favorites: [] }
])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2, '2': 3 } }
$push (read "push") adds an item to the end of an array. Maya taps the heart on Pad Thai:
db.cooks.updateOne({ _id: 1 }, { $push: { favorites: "Pad Thai" } })
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
Her phone lags, and she taps again. $push adds it again:
db.cooks.updateOne({ _id: 1 }, { $push: { favorites: "Pad Thai" } })
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
db.cooks.findOne({ _id: 1 })
{
_id: 1,
name: 'Maya',
favorites: [ 'Chickpea Curry', 'Black Bean Tacos', 'Pad Thai', 'Pad Thai' ]
}
$pull (read "pull") removes every item equal to the value, so one $pull cleans up both copies:
db.cooks.updateOne({ _id: 1 }, { $pull: { favorites: "Pad Thai" } })
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
$addToSet: only if it isn't there yet
A set, in math and in programming, is a collection with no repeats. $addToSet (read "add to set") adds an item only when the array doesn't already hold it, so the second tap changes nothing:
db.cooks.updateOne({ _id: 1 }, { $addToSet: { favorites: "Pad Thai" } })
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
db.cooks.updateOne({ _id: 1 }, { $addToSet: { favorites: "Pad Thai" } })
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 0,
upsertedCount: 0
}
The first call modified Maya's list; the second matched her but modified nothing, and her favorites hold Pad Thai once. Choose $push when repeats mean something, such as a log of every night a recipe was cooked, and $addToSet when they don't, such as favorites.
Check yourself
2 questions to try on the lesson page.
So what
Counts that never lose a tap and lists that never fill up with duplicates: with $inc, $push, $pull and $addToSet, the database does that work for you, one change at a time.