運算子 $bit 可用來對整數值執行位運算。 它可用來套用位 AND、OR 和 XOR 作業,以更新檔中的整數位段。 $bit之類的位運算符不是為了遞增值而設計,而是為了直接操作位(例如檢查、設定或清除特定位)。
語法
{
$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
}
]