$bit
运算符用于对整数值执行位运算。 该运算符可用于通过应用 AND、OR 和 XOR 等位运算更新文档中的整数字段。 $bit 之类的位运算符并非用于递增值,而是用于直接操作位(例如检查、设置或清除特定位)。
语法
{ $bit: { <field>: { <operator>: <number> } } }
parameters
说明 | |
---|---|
<field> |
要执行位运算的字段。 |
<operator> |
要执行的位运算。 可以是以下选项之一:and 、or 、xor 。 |
<number> |
要用于位运算的数字。 |
示例
让我们通过以下示例 json 来了解用法。
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile",
"location": {
"lat": 60.1441,
"lon": -141.5012
},
"staff": {
"totalStaff": {
"fullTime": 2,
"partTime": 0
}
},
"sales": {
"salesByCategory": [
{
"categoryName": "DJ Headphones",
"totalSales": 35921
}
],
"fullSales": 3700
},
"promotionEvents": [
{
"eventName": "Bargain Blitz Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 3,
"Day": 11
},
"endDate": {
"Year": 2024,
"Month": 2,
"Day": 18
}
},
"discounts": [
{
"categoryName": "DJ Turntables",
"discountPercentage": 18
},
{
"categoryName": "DJ Mixers",
"discountPercentage": 15
}
]
}
],
"tag": [
"#ShopLocal",
"#SeasonalSale",
"#FreeShipping",
"#MembershipDeals"
]
}
示例 1:在 totalStaff
中对 partTime
字段执行 AND 位运算。
db.stores.updateOne(
{ "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" },
{ $bit: { "staff.totalStaff.partTime": { and: 1 } } }
)
此查询将返回以下文档。 0 和 1 的 AND 为 0,因此该字段的新值为 0。
{
"acknowledged": true,
"insertedId": null,
"matchedCount": "1",
"modifiedCount": "1",
"upsertedCount": 0
}
示例 2:在 totalStaff
中对 partTime
字段执行 OR 位运算。
db.stores.updateOne(
{ "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" },
{ $bit: { "staff.totalStaff.partTime": { "or" : 1 } } }
)
此查询将返回以下文档。 0 和 1 的 OR 为 1,因此该字段的新值为 1。
{
"acknowledged": true,
"insertedId": null,
"matchedCount": "1",
"modifiedCount": "1",
"upsertedCount": 0
}
示例 3:在 totalStaff
中对 partTime
字段执行 XOR 位运算。
db.stores.updateOne(
{ "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" },
{ $bit: { "staff.totalStaff.partTime": { "xor" : 1 } } }
)
此查询将返回以下文档。 1 和 1 的 XOR 为 0,因此该字段的新值为 0。
{
"acknowledged": true,
"insertedId": null,
"matchedCount": "1",
"modifiedCount": "1",
"upsertedCount": 0
}