I have an array that is like [1,2,1,2,3,5,2]. And I want to remove only one element amongst the selected elements. I used $pull operator and it doesn’t work as I required, it remove all elements I specified.
db.user.updateOne({_id: ...}, {$pull:{'array': 1}})
I tried it and give this result: [2,2,3,5,2].
is there any way to get the result: [2,1,2,3,5,2]
2
Answers
This feature does not exist (and won’t), as you can see in this Jira. ticket they choose they won’t do this.
Here is a hacky work around – the strategy will be to find the index of the first matching element and slice it out of the array, like so:
Mongo Playground
Query
{"n-ar": [], "found": false}
found=true
$concat
to add the member to the new-ar*it can be generalized, like remove the first 4 occurences, if integer is used as found
*its pipeline update requires MongoDB >= 4.2
Playmongo