On this page
$bit
在本页面
Definition
{ $bit: { <field>: { <and|or|xor>: <int> } } }
仅将此运算符与整数字段(32 位整数或 64 位整数)一起使用。
要在嵌入式文档或数组中指定<field>,请使用dot notation。
Note
mongo shell 中的所有数字都是双精度,而不是整数。使用NumberInt()或NumberLong()构造函数指定整数。有关更多信息,请参见NumberInt或NumberLong。
Examples
Bitwise AND
考虑将以下文档插入集合switches中:
{ _id: 1, expdata: NumberInt(13) }
以下update()操作将expdata字段更新为当前值NumberInt(13)(即1101)和NumberInt(10)(即1010)之间按位and的结果:
db.switches.update(
{ _id: 1 },
{ $bit: { expdata: { and: NumberInt(10) } } }
)
按位and运算得到整数 8(即1000):
1101
1010
----
1000
并且更新后的文档的expdata具有以下值:
{ "_id" : 1, "expdata" : 8 }
mongoShell 将NumberInt(8)显示为8。
Bitwise OR
考虑将以下文档插入集合switches中:
{ _id: 2, expdata: NumberLong(3) }
以下update()操作将expdata字段更新为当前值NumberLong(3)(即0011)和NumberInt(5)(即0101)之间按位or的结果:
db.switches.update(
{ _id: 2 },
{ $bit: { expdata: { or: NumberInt(5) } } }
)
按位or运算得出整数 7(即0111):
0011
0101
----
0111
并且更新后的文档的expdata具有以下值:
{ "_id" : 2, "expdata" : NumberLong(7) }
Bitwise XOR
考虑集合switches中的以下文档:
{ _id: 3, expdata: NumberLong(1) }
以下update()操作将expdata字段更新为当前值NumberLong(1)(即0001)和NumberInt(5)(即0101)之间按位xor的结果:
db.switches.update(
{ _id: 3 },
{ $bit: { expdata: { xor: NumberInt(5) } } }
)
按位xor运算得出整数 4:
0001
0101
----
0100
并且更新后的文档的expdata具有以下值:
{ "_id" : 3, "expdata" : NumberLong(4) }