对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

$bit(更新操作符)

$bit

$bit 操作符对字段执行按位更新。该操作符支持按位 and、按位 or 和按位 xor(即异或)操作。要指定 $bit 操作符表达式,请使用以下原型:

{ $bit: { <field>: { <and|or|xor>: <int> } } }

此操作符仅用于整数字段(32 位整数或 64 位整数)。

要在嵌入式文档或数组中指定 <field>,请使用点符号。

注意

mongosh 中的所有数字都是 double,而不是整数。要在 mongosh 中指定整数,请使用 Int32() 或 Long() 构造函数。如需了解更多信息,请参阅 Int32 或 长整型 (Long)。

如需了解 MongoDB 驱动程序如何处理数值,请参阅驱动程序的文档。

从MongoDB5.0 开始,当您将 等更新操作符符与空操作数表达式()mongod $bit一起使用时,{ } 不再引发错误。空更新不会导致任何更改,也不会创建oplog条目(意味着该操作为“不操作”)。

从 MongoDB 5.0 开始,更新操作符按字典顺序处理具有基于字符串的名称的文档字段。具有数字名称的字段按数字顺序处理。详情请参阅更新操作符行为。

以下示例使用 switches 集合:

db.switches.insertMany( [
{ _id: 1, expdata: Int32(13) },
{ _id: 2, expdata: Int32(3) },
{ _id: 3, expdata: Int32(1) }
] )

在 updateOne() 操作中使用按位 and 更新 expdata。

db.switches.updateOne(
{ _id: 1 },
{ $bit: { expdata: { and: Int32( 10 ) } } }
)

按位 and 操作:

  • 获取按位值: expdata

  • 使用 and 应用 Int32(10) 的按位值

  • 用结果 1000 更新 expdata

1101 // expdata
1010 // Int32(10)
----
1000

二进制 1000 等效于 Int32(8)。db.switches.find( { _id: 1 } ) 命令将返回以下文档:

{ "_id" : 1, "expdata" : 8 }

在 updateOne() 操作中使用按位 or 更新 expdata。

db.switches.updateOne(
{ _id: 2 },
{ $bit: { expdata: { or: Int32( 5 ) } } }
)

按位 or 操作:

  • 获取按位值: expdata

  • 使用 or 应用 Int32(5) 的按位值

  • 使用结果 0111 更新 expdata

0111 // expdata
0101 // Int32(5)
----
0111

二进制 0111 等效于 Int32(7)。db.switches.find( { _id: 2 } ) 命令将返回以下文档:

{ "_id" : 2, "expdata" : 7 }

在 updateOne() 操作中使用按位 xor 更新 expdata。

db.switches.updateOne(
{ _id: 3 },
{ $bit: { expdata: { xor: Int32( 5 ) } } }
)

按位 and 操作:

  • 获取按位值: expdata

  • 使用 and 应用 Int32(5) 的按位值

  • 使用结果 0100 更新 expdata

0001 // expdata
0101 // Int32(5)
----
0100

二进制 0100 相当于 Int32(4)。db.switches.find( { _id: 3 } ) 命令返回以下文档:

{ "_id" : 1, "expdata" : 4 }
给本页内容打分

在此页面上