Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongodDB $pull only one element from array [duplicate]

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?

like image 742
JVG Avatar asked Dec 09 '13 04:12

JVG


People also ask

How do I remove one item from an array in MongoDB?

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.

How do you update an array element in MongoDB?

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.

What is pull in MongoDB?

The $pull operator is used to remove all the instances of a value or values from a MongoDB document that matches a specified condition.


1 Answers

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:

  1. find element that you want and that has userTags as foo
  2. iterate through userTags and remove one foo from it
  3. 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.

like image 72
Salvador Dali Avatar answered Sep 19 '22 08:09

Salvador Dali