Pull and addtoset at the same time with mongo

The error is pretty much what it means as you cannot act on two things of the same “path” in the same update operation. The two operators you are using do not process sequentially as you might think they do.

You can do this with as “sequential” as you can possibly get with the “bulk” operations API or other form of “bulk” update though. Within reason of course, and also in reverse:

var bulk = db.coll.initializeOrderedBulkOp();
bulk.find({ "tags": 1 }).updateOne({ "$addToSet": { "tags":  2 } });
bulk.find({ "tags": 1 }).updateOne({ "$pull": { "tags": 1 } });

bulk.execute();

Not a guarantee that nothing else will try to modify,but it is as close as you will currently get.

Also see the raw “update” command with multiple documents.

Leave a Comment