该 $bit 运算符用于对整数值执行按位运算。 它可用于通过应用按位 AND、OR 和 XOR 操作更新文档中的整数字段。 $bit之类的按位运算符不是用于递增值,而是用于直接操作位(例如检查、设置或清除特定位)。
Syntax
{
$bit: {
< field >: {
< operator >: < number >
}
}
}
参数
| 参数 | Description |
|---|---|
<field> |
要对该字段执行按位运算的字段。 |
<operator> |
要执行的按位运算。 可以是以下项之一: and, or。 xor |
<number> |
要用于按位运算的数字。 |
例子
请考虑商店集合中的这个示例文档。
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"location": {
"lat": -89.2384,
"lon": -46.4012
},
"staff": {
"totalStaff": {
"fullTime": 8,
"partTime": 20
}
},
"sales": {
"totalSales": 75670,
"salesByCategory": [
{
"categoryName": "Wine Accessories",
"totalSales": 34440
},
{
"categoryName": "Bitters",
"totalSales": 39496
},
{
"categoryName": "Rum",
"totalSales": 1734
}
]
},
"promotionEvents": [
{
"eventName": "Unbeatable Bargain Bash",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 6,
"Day": 23
},
"endDate": {
"Year": 2024,
"Month": 7,
"Day": 2
}
},
"discounts": [
{
"categoryName": "Whiskey",
"discountPercentage": 7
},
{
"categoryName": "Bitters",
"discountPercentage": 15
},
{
"categoryName": "Brandy",
"discountPercentage": 8
},
{
"categoryName": "Sports Drinks",
"discountPercentage": 22
},
{
"categoryName": "Vodka",
"discountPercentage": 19
}
]
},
{
"eventName": "Steal of a Deal Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Organic Wine",
"discountPercentage": 19
},
{
"categoryName": "White Wine",
"discountPercentage": 20
},
{
"categoryName": "Sparkling Wine",
"discountPercentage": 19
},
{
"categoryName": "Whiskey",
"discountPercentage": 17
},
{
"categoryName": "Vodka",
"discountPercentage": 23
}
]
}
]
}
示例 1:对 partTime 字段执行按位 AND作 totalStaff
db.stores.updateOne({
_id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"
}, {
$bit: {
"staff.totalStaff.partTime": {
and: 1
}
}
})
此查询返回以下结果。
[
{
"acknowledged": true,
"insertedId": null,
"matchedCount": "1",
"modifiedCount": "1",
"upsertedCount": 0
}
]
示例 2:对 partTime 字段执行按位 OR作 totalStaff
db.stores.updateOne({
_id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"
}, {
$bit: {
"staff.totalStaff.partTime": {
"or": 1
}
}
})
此查询返回以下结果。
[
{
"acknowledged": true,
"insertedId": null,
"matchedCount": "1",
"modifiedCount": "1",
"upsertedCount": 0
}
]
示例 3:对 partTime 字段执行按位 XOR作 totalStaff
db.stores.updateOne({
_id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"
}, {
$bit: {
"staff.totalStaff.partTime": {
"xor": 1
}
}
})
此查询返回以下结果。
[
{
"acknowledged": true,
"insertedId": null,
"matchedCount": "1",
"modifiedCount": "1",
"upsertedCount": 0
}
]
相关内容
- 查看用于 从 MongoDB 迁移到 Azure DocumentDB 的选项。
- 详细了解 与 MongoDB 的功能兼容性。