$bitAnd演算子は、整数値に対してbitwise AND演算を実行します。 最初のオペランドの各ビットを、2 番目のオペランドの対応するビットと比較します。 両方のビットが 1 の場合、対応する結果のビットは 1 に設定されます。 それ以外の場合は、対応する結果ビットが 0 に設定されます。
構文
{
$bitAnd: [ <expression1>, <expression2>, ... ]
}
パラメーター
| パラメーター | Description |
|---|---|
expression1, expression2, ... |
整数に評価される式。
$bitAnd演算子は、指定されたすべての式に対してビットごとの AND 演算を実行します。 |
例示
stores コレクションのこのサンプル ドキュメントについて考えてみましょう。
{
"_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: 基本的なビットごとの AND 演算
このクエリは、特定のストアのスタッフ情報を取得し、フルタイムスタッフとパートタイム スタッフの数の間の bitwise AND を計算してアクセス許可フラグを作成します。
db.stores.aggregate([{
$match: {
_id: "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"
}
},
{
$project: {
name: 1,
fullTimeStaff: "$staff.totalStaff.fullTime",
partTimeStaff: "$staff.totalStaff.partTime",
staffPermissionFlag: {
$bitAnd: ["$staff.totalStaff.fullTime", "$staff.totalStaff.partTime"]
}
}
}
])
このクエリは、次の結果を返します。
[
{
"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74",
"name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury",
"fullTimeStaff": 19,
"partTimeStaff": 20,
"staffPermissionFlag": 16
}
]
例 2: 複数の値 $bitAnd
このクエリは、1 つのストアの複数の数値フィールドに基づいて、ビットごとのアクセス許可または結合フラグをチェックします。
db.stores.aggregate([{
$match: {
_id: "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"
}
},
{
$project: {
name: 1,
combinedFlag: {
$bitAnd: [
"$staff.totalStaff.fullTime",
"$staff.totalStaff.partTime",
255
]
}
}
}
])
このクエリは、次の結果を返します。
[
{
"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74",
"name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury",
"combinedFlag": 16
}
]