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?
To remove an element, update, and use $pull in MongoDB. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.
You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.
The $pull operator is used to remove all the instances of a value or values from a MongoDB document that matches a specified condition.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With