我的情况是:我在 Users 集合中有一个文档,例如:
Users : {
_id : "id_str",
active : 1
}
我想用只有一个查询
更新这个用户的active
状态,比如:
Users.update({
_id : "id_str"
}, {
$set : {
active : 0 if active now is 1, 1 if active now is 0
}
})
我不是在寻找任何找到 user document
以获得 active
状态然后更新它的解决方案。我只想使用 1 个查询来解决这个问题
在MySQL中,我经常只用一条SQL解决这个问题:
更新用户 SET active = ABS(active - 1) WHERE...
但我不知道如何在 MongoDB 中做到这一点。请帮我。 提前致谢
最佳答案
您可以使用 $bit
执行此操作和 xor
运算符,但您需要确保您的值是整数,而不是 shell 中默认值的两倍。
因此,如果您将文档创建为:
db.users.insert([{
_id : "id_str1",
active : NumberInt(0)
},{
_id : "id_str2",
active : NumberInt(1)
}])
您可以使用以下方式切换它们的 active
值:
db.users.update({}, {$bit: {active: {xor: NumberInt(1)}}}, {multi: true})
关于javascript - MongoDB:用反值更新字段编号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35643324/