Can mongo upsert array data?

I’m not aware of an option that would upsert into an embedded array as at MongoDB 2.2, so you will likely have to handle this in your application code.

Given that you want to treat the embedded array as sort of a virtual collection, you may want to consider modelling the array as a separate collection instead.

You can’t do an upsert based on a field value within an embedded array, but you could use $addToSet to insert an embedded document if it doesn’t exist already:

db.soup.update({
    "tester":"tom"
}, {
    $addToSet: {
        'array': {
            "id": "3",
            "letter": "d"
        }
    }
})

That doesn’t fit your exact use case of matching by id of the array element, but may be useful if you know the expected current value.

Leave a Comment