5

With a schema like this :

{
        "_id" : ObjectId("513fe2b85b51eafc15000023"),
        "tags" : [
                "House",
                "Red"
        ]
}

How would you do the following:

If the tag exists remove it, if it doesn't exist add it.

2
  • Do you query based on the _id field?
    – assylias
    Apr 2, 2013 at 17:11
  • Did you get a solution? I am looking for one update statement to toggle tags in a array as well.
    – Ron
    Apr 1, 2016 at 21:33

1 Answer 1

1

The operator $addToSet and $pull. $addToSet will only add the tag if it doesn't exist. $pull will remove all instances of the tag.

As @assylias mentioned, you would construct a full update command with the _id presumabley, or in conjunction with {tags: tagInQuestion} to only operate on a document that has tagInQuestion etc.

1
  • 1
    Yeah, but how to know when to use one over the other, suposing that you're using a GraphQL API and can't diferentiate by the HTTP verb used.
    – user7075574
    Apr 15, 2020 at 3:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.