MongodDB $pull only one element from array
arrays, database, mongodb, nosql
Solution
No, there is nothing like this at the moment. A lot of people already requested the feature and you can track it in mongodb Jira. As far as you can see it is not resolved and also not scheduled (which means you have no luck in the near future).
The only option is to use application logic to achieve this would be:
- find element that you want and that has userTags as foo
- iterate through userTags and remove one foo from it
- update that element with a new userTags
Keep in mind that this operation breaks atomicity, but because Mongo has not provided a native method to do so, you will break atomicity in any way.
I moved one alternative solution to the new answer, because it does not answer this question, but represents one of the approaches to refactor existing schema. It also became so big, that started to be much bigger then the original answer.
Problem
I have a document with an array inside, like this: ``` "userTags" : [ "foo", "foo", "foo", "foo", "moo", "bar" ] ``` If I perform `db.products.update({criteriaToGetDocument}, {$push: {userTags: "foo"}}}` I can correctly insert another instance of `foo` into the array. However, if I do `db.products.update({criteriaToGetDocument}, {$pull: {userTags: "foo"}}}` then it removes all instances of `foo` from the array, leaving me with: ``` "userTags" : [ "moo", "bar" ] ``` This won't do at all, I only want to pull one item from the array rather than all of them. How can I alter the command so that only one `foo` is removed? Is there some sort of `$pullOnce` method that can work here?