I just ran into this problem myself. I wasn’t able to find a one-call solution, but I found a two-call solution that works when you have a unique value in your array elements. Use the $pull
command first, which removes elements from an array, and then $push
.
db.soup.update({
"tester":"tom"
}, {
$pull: {
'array': {
"id": "3"
}
}
})
db.soup.update({
"tester":"tom"
}, {
$push: {
'array': {
"id": "3",
"letter": "d"
}
}
})
This should work when the document doesn’t exist, when the document exists but the entry in the array doesn’t exist, and when the entry exists.
Again, this only works if you have something, like the id
field in this example, that should be unique across elements of the array.