在 MongoDB 中使用按位或

Using Bitwise OR in MongoDB

我正在做一个项目,我想在我的 Mongo 数据库中切换 0 和 1 之间的值。我已将每个值从默认双精度设置为 32 位 Int。但是,每次我 运行 这段代码,我都会得到这个错误:

> db.players.update({name: "Patrick Mahomes"}, {$bit: {active: {xor:1}}})
WriteResult({
        "nMatched" : 0,
        "nUpserted" : 0,
        "nModified" : 0,
        "writeError" : {
                "code" : 2,
                "errmsg" : "The $bit modifier field must be an Integer(32/64 bit); a 
'double' is not supported here: {xor: 1.0}"
        }

知道为什么会这样吗?当我查询活动字段类型时,它 returns 我数据库中的所有对象。

> db.players.find({active: {$type:16}})

这最终将成为在网站上单击按钮以在两种不同状态之间切换的功能。

您能否尝试使用 NumberInt 提供值。

db.players.update({name: "Patrick Mahomes"}, {$bit: {active: {xor:NumberInt(1)}}})

检查文档here.

在 mongo shell 中传递的数字被推断为 double 以匹配 javascript 风格的约定。所以 {xor: 1} 中的 1double

您需要指定 NumberInt(1) 以获得 32 位整数(或 NumberLong(1) 以获得 64 位整数)。

此行为已记录 here