Now what else can we do with update besides setting some values?
Let's look into our users again and let's say Manuel got older, he's 30 but let's say we want to increase
that to 31.
Now obviously, this is pretty straightforward to us,
we could use $set and set age to 31
but in a typical application, you will not know the age of all your users,
so it would be nice if you wouldn't have to find all users or the user you want to update first to get
the current age then recalculate the new age and then issue your update request, would be nice
if for simple and common transformations like this, mongodb would do that
and indeed it can. Incrementing a number,
so increasing it is such a common task that mongodb has a built-in operator for this.
So let's quickly grab the ID or let's filter by name to mix it up,
so let's filter for Manuel, db users update one
and then here, I'm looking for a name equal to Manuel,
this will find the first entry or the first document with a name of Manuel in the collection
and then here in a second argument, I don't use $set but I use the inc,
so $inc, by the way you can also combine this. You can have $inc
and then here you have some information which I'll add in a second
and then as a second element in this second argument, so in this object with the purple curly brace, you
can of course add $set and describe some other changes,
so you can do multiple different things in the same update.
But here I'll just use $inc and I will say that the age should be incremented by 1,
this is what this will do
and we could also increment by two,
so if I do that for example and I find all results, Manuel now has an age of 32,
it was 30 before.
Now you can also decrement with this method even though it's called inc,
you can also say -1 for example
and now it will be 31 as you can see here.
So with inc, you can go in both directions
and as I mentioned, you can combine it and just to show this because it's really important,
you can absolutely say increment by 1 and then $set
and for example set isSporty which is missing to false because Manuel doesn't have sports as a hobby.
If you do that, then you see it also succeeded and it simply did both
and if we check Manuel again, he's now 32 and isSporty was added with a value of false.
Now of course you could also get fancy and you could try setting the same value you're incrementing,
so I'm incrementing age by 1 and then I'm setting age to 30,
now let's see what happens now.
If I do that, then I get an error,
I get an error that updating the path age would create a conflict at age because I simply got two operations
working on the same field
and this is not allowed here,
so it will simply fail.
So you can use inc and set
and the other operators I'll show you together but working on the same field will not be possible.