How do I update all of a specific element in an array in mongoDB?

Viewed 24

I have the following data:

{
    "name": "tom",
    "songs": [
        { "songname": "hello", "day": "20" },
        { "songname": "goodbye", "day": "25" },
        { "songname": "morning", "day": "15" }],
    "solo": "yes"
}

I want to increment the day of each of the songs in the array by 2 for the person with the name tom. I figured using $inc such as

db.collection.update({ "name": "tom" }, { "$inc": { "songs.day": 2 } })

would work but it doesnt work. I get the error "errmsg" : "The positional operator did not find the match needed from the query."

1 Answers

first of all, for $inc to work, you need to store your day values as numbers/ints. $inc doesn't work on strings.

then simply use the all positional operator $[] like so:

db.collection.update(
    { "name": "tom" },
    { "$inc": { "songs.$[].day": 2 } }
)
Related