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? Commented 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. Commented 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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.