Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle tags in a MongoDB array?

Tags:

mongodb

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.

like image 664
standac Avatar asked Nov 13 '22 08:11

standac


1 Answers

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.

like image 135
Nuk Nuk San Avatar answered Nov 15 '22 11:11

Nuk Nuk San