你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
适用对象: MongoDB vCore
该 $bitNot
运算符对整数值执行按位 NOT 运算。 它将作数的所有位反转,将 1 转换为 0 和 0 转换为 1。 结果是输入值的按位补数。
语法
运算符的 $isArray
语法如下所示:
{
$bitNot: <expression>
}
参数
DESCRIPTION | |
---|---|
expression |
计算结果为整数的表达式。 运算符 $bitNot 对此值执行按位 NOT 运算。 |
示例:
让我们了解 stores
数据集中的示例 json 的用法。
{
"_id": "26afb024-53c7-4e94-988c-5eede72277d5",
"name": "First Up Consultants | Microphone Bazaar - South Lexusland",
"location": {
"lat": -29.1866,
"lon": -112.7858
},
"staff": {
"totalStaff": {
"fullTime": 14,
"partTime": 8
}
},
"sales": {
"totalSales": 83865,
"salesByCategory": [
{
"categoryName": "Lavalier Microphones",
"totalSales": 44174
},
{
"categoryName": "Wireless Microphones",
"totalSales": 39691
}
]
},
"promotionEvents": [
{
"eventName": "Incredible Savings Showcase",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Condenser Microphones",
"discountPercentage": 20
},
{
"categoryName": "Microphone Stands",
"discountPercentage": 17
}
]
}
]
}
示例 1:基本按位 NOT作
对员工编号执行按位 NOT作以创建倒排标志。
db.stores.aggregate([
{ $match: {"_id": "26afb024-53c7-4e94-988c-5eede72277d5"} },
{
$project: {
name: 1,
fullTimeStaff: "$staff.totalStaff.fullTime",
partTimeStaff: "$staff.totalStaff.partTime",
invertedFullTime: {
$bitNot: "$staff.totalStaff.fullTime"
},
invertedPartTime: {
$bitNot: "$staff.totalStaff.partTime"
}
}
}
])
这会生成以下输出:
[
{
_id: '26afb024-53c7-4e94-988c-5eede72277d5',
name: 'First Up Consultants | Microphone Bazaar - South Lexusland',
fullTimeStaff: 14,
partTimeStaff: 8,
invertedFullTime: -15,
invertedPartTime: -9
}
]
按位 NOT 为 14 会导致 -15,8 位的按位 NOT 结果为 -9。 这是因为两人的补数表示形式 ,其中 ~n = -(n+1)。
示例 2:将$bitNot与折扣百分比配合使用
对折扣百分比应用按位 NOT作。
db.stores.aggregate([
{ $match: {"_id": "26afb024-53c7-4e94-988c-5eede72277d5"} },
{ $unwind: "$promotionEvents" },
{ $match: {"promotionEvents.eventName": "Incredible Savings Showcase"} },
{ $unwind: "$promotionEvents.discounts" },
{
$project: {
name: 1,
eventName: "$promotionEvents.eventName",
categoryName: "$promotionEvents.discounts.categoryName",
discountPercentage: "$promotionEvents.discounts.discountPercentage",
invertedDiscount: {
$bitNot: "$promotionEvents.discounts.discountPercentage"
}
}
}
])
这会生成以下输出:
[
{
_id: '26afb024-53c7-4e94-988c-5eede72277d5',
name: 'First Up Consultants | Microphone Bazaar - South Lexusland',
eventName: 'Incredible Savings Showcase',
categoryName: 'Condenser Microphones',
discountPercentage: 20,
invertedDiscount: -21
},
{
_id: '26afb024-53c7-4e94-988c-5eede72277d5',
name: 'First Up Consultants | Microphone Bazaar - South Lexusland',
eventName: 'Incredible Savings Showcase',
categoryName: 'Microphone Stands',
discountPercentage: 17,
invertedDiscount: -18
}
]
按位 NOT 运算将反转所有位:20 变为 -21,17 变为 -18。