MongoDB 如何从数组中删除值(如果存在),否则添加

sud*_*hin 3 mongodb

我有文件

 {
    "_id" : ObjectId("5aebf141a805cd28433c414c"),
    "forumId" : ObjectId("5ae9f82989f7834df037cc90"),
    "userName" : "Name",
    "usersLike" : [ 
        "1","2"
    ],
    "comment" : "Comment",
}
Run Code Online (Sandbox Code Playgroud)

如果值存在,我想从 usersLike 数组中删除值,如果值不存在,则添加。

例如:

如果我尝试将 1 推入 usersLike,它应该返回

{
    "_id" : ObjectId("5aebf141a805cd28433c414c"),
    "forumId" : ObjectId("5ae9f82989f7834df037cc90"),
    "userName" : "Name",
    "usersLike" : [ 
        "2"
    ],
    "comment" : "Comment",
}
Run Code Online (Sandbox Code Playgroud)

怎么查询呢..?

Tom*_*ert 5

MongoDB 版本 4.2+ 引入了管道更新。这意味着我们现在可以在更新时使用聚合运算符。这给了我们很大的力量。

db.collection.updateOne(
    {
        _id: ObjectId("597afd8200758504d314b534")
    },
    [
        {
            $set: {
                usersLike: {
                    $cond: [
                        {
                            $in: ["1", "$usersLike"]
                        },
                        {
                            $setDifference: ["$usersLike", ["1"]]
                        },
                        {
                            $concatArrays: ["$usersLike", ["1"]]
                        }
                    ]
                }
            }
        }
    ]
)
Run Code Online (Sandbox Code Playgroud)