适用对象:
MongoDB vCore
当至少一个表达式的计算结果为$or
时,运算符true
返回 true
。 它在表达式数组上执行逻辑 OR作。 如果所有表达式的计算结果 false
为,则整个 $or
表达式返回 false
。 此运算符可用于创建可满足任意一个条件的灵活条件。
语法
$or
运算符的语法如下:
{
$or: [ <expression1>, <expression2>, ... ]
}
参数
DESCRIPTION | |
---|---|
<expression1>, <expression2>, ... |
要计算的两个或多个表达式。 如果任何表达式的计算结果 true 为,则 $or 运算返回 true 。 |
示例:
让我们了解 stores
数据集中的示例 json 的用法。
{
"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f",
"name": "First Up Consultants | Bed and Bath Center - South Amir",
"location": {
"lat": 60.7954,
"lon": -142.0012
},
"staff": {
"totalStaff": {
"fullTime": 18,
"partTime": 17
}
},
"sales": {
"totalSales": 37701,
"salesByCategory": [
{
"categoryName": "Mattress Toppers",
"totalSales": 37701
}
]
},
"promotionEvents": [
{
"eventName": "Price Drop Palooza",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 30
}
},
"discounts": [
{
"categoryName": "Bath Accessories",
"discountPercentage": 18
},
{
"categoryName": "Pillow Top Mattresses",
"discountPercentage": 17
}
]
}
]
}
示例 1:识别具有高销售额或大型员工的商店
该示例查找总销售额大于 50,000 或超过 25 名员工总数的商店。
db.stores.aggregate([
{
$project: {
name: 1,
totalSales: "$sales.totalSales",
totalStaff: {
$add: ["$staff.employeeCount.fullTime", "$staff.employeeCount.partTime"]
},
qualifiesForProgram: {
$or: [
{ $gt: ["$sales.totalSales", 50000] },
{ $gt: [{ $add: ["$staff.employeeCount.fullTime", "$staff.employeeCount.partTime"] }, 25] }
]
}
}
},
{ $limit: 4 }
])
该查询返回满足销售或人员配备条件的商店。
{
"_id": "905d1939-e03a-413e-a9c4-221f74055aac",
"name": "Trey Research | Home Office Depot - Lake Freeda",
"totalStaff": 31,
"qualifiesForProgram": true
},
{
"_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6",
"name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort",
"totalStaff": 27,
"qualifiesForProgram": true
},
{
"_id": "923d2228-6a28-4856-ac9d-77c39eaf1800",
"name": "Lakeshore Retail | Home Decor Hub - Franciscoton",
"totalStaff": 13,
"qualifiesForProgram": false
},
{
"_id": "7e53ca0f-6e24-4177-966c-fe62a11e9af5",
"name": "Contoso, Ltd. | Office Supply Deals - South Shana",
"totalStaff": 2,
"qualifiesForProgram": false
}
示例 2:检查折扣资格
该示例确定商店是否提供高百分比(>15%)或特定热门类别的折扣。
db.stores.aggregate([
{ $match: {"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f"} },
{
$project: {
_id: 1,
name: 1,
hasAttractiveDealOptions: {
$or: [
{ $gt: [{ $max: "$promotionEvents.discounts.discountPercentage" }, 15] },
{ $in: ["Bath Accessories", "$promotionEvents.discounts.categoryName"] },
{ $in: ["Mattress Toppers", "$promotionEvents.discounts.categoryName"] }
]
}
}
}
])
查询检查商店是否具有高折扣百分比或热门类别的交易。
{
"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f",
"name": "First Up Consultants | Bed and Bath Center - South Amir",
"hasAttractiveDealOptions": true
}