Pull and addtoset at the same time with mongo

前端 未结 4 2037
别那么骄傲
别那么骄傲 2020-12-01 14:21

I have a collection which elements can be simplified to this:

{tags : [1, 5, 8]}

where there would be at least one element in array and all of t

4条回答
  •  无人及你
    2020-12-01 14:43

    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.

提交回复
热议问题