I’m trying to make a seemingly simple update to a MongoDB collection that looks like the below using Node.
Collection
{
account_id: "ORG1",
progress: [{week: 1, goal: 5000, raised: 2400}, {week: 2, goal:5100, raised: 1000}]
}
The goal is to be able to
- Find the correct org (this works for me)
- Add a value to the last array entry’s "raised" value. (e.g. Initially the raised value is 1000, after my update, it will be 1000 + an incoming value).
My hacky approach would be to do a find query to get the initial value and then do an update to add my incoming value to the initial value. But I’m sure there’s a simpler way.
Thanks in advance!
3
Answers
I ended up finding a solution that feels a bit simpler than the solutions I've seen.
I added a field to the db called "status":
Then I ended up using the positional operator ($) and increment functions.
Worked smoothly.
One option is using an update pipeline:
$concatArrays
See how it works on the playground example – concatArrays
Another option is using
$reduce
:Here we are iterating on the array, for each item checking if it is the last one, and if so updating it:
See how it works on the playground example – reduce
One way to do it is by using
"$function"
in the update/aggregation pipeline.Try it on mongoplayground.net.