适用对象:
MongoDB vCore
该 $or
运算符对表达式数组执行逻辑 OR作,并选择至少满足其中一个表达式的文档。
语法
{ $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }
参数
参数 | 类型 | DESCRIPTION |
---|---|---|
expression |
数组 | 表达式数组,其中至少一个表达式必须为 true 才能包含文档 |
例子
示例 1:基本 OR作
查找拥有 15 多名全职员工或 20 多名兼职员工的商店:
db.stores.find({
$or: [
{ "staff.totalStaff.fullTime": { $gt: 15 } },
{ "staff.totalStaff.partTime": { $gt: 20 } }
]
})
输出:
{
_id: 'd924d148-9e01-4ab1-91d6-9daccb12a4dd',
name: 'Fourth Coffee | Home Entertainment Gallery - East Adellahaven',
location: { lat: -86.4872, lon: 130.9398 },
staff: { totalStaff: { fullTime: 16, partTime: 14 } },
sales: {
totalSales: 179639,
salesByCategory: [
{ categoryName: 'Home Theater Systems', totalSales: 18707 },
{ categoryName: 'Xbox Games', totalSales: 48276 },
{ categoryName: 'Sound Bars', totalSales: 43142 },
{ categoryName: 'Projector Mounts', totalSales: 43358 },
{ categoryName: 'Televisions', totalSales: 11325 },
{ categoryName: 'Streaming Devices', totalSales: 14831 }
]
},
promotionEvents: [
{
eventName: 'Massive Deal Mania',
promotionalDates: {
startDate: { Year: 2024, Month: 9, Day: 21 },
endDate: { Year: 2024, Month: 9, Day: 29 }
},
discounts: [
{
categoryName: 'Home Theater Projectors',
discountPercentage: 16
},
{ categoryName: 'TV Mounts', discountPercentage: 17 },
{ categoryName: 'Projector Lamps', discountPercentage: 24 },
{ categoryName: 'Sound Bars', discountPercentage: 8 },
{ categoryName: 'Media Players', discountPercentage: 14 },
{
categoryName: 'Nintendo Switch Games',
discountPercentage: 22
}
]
}
]
}..
示例 2:复杂 OR作
查找总销售额超过 100000 或折扣超过 20%的商店:
db.stores.find({
$or: [
{ "sales.totalSales": { $gt: 100000 } },
{ "promotionEvents.discounts.discountPercentage": { $gt: 20 } }
]
})
输出:
{
eventName: 'Bargain Blitz Bash',
promotionalDates: {
startDate: { Year: 2024, Month: 3, Day: 25 },
endDate: { Year: 2024, Month: 4, Day: 3 }
},
discounts: [
{ categoryName: 'Pet Carriers', discountPercentage: 22 },
{ categoryName: 'Pet Collars', discountPercentage: 11 }
]
},
{
eventName: 'Clearance Carnival',
promotionalDates: {
startDate: { Year: 2024, Month: 6, Day: 23 },
endDate: { Year: 2024, Month: 6, Day: 30 }
},
discounts: [
{ categoryName: 'Cat Litter', discountPercentage: 18 },
{ categoryName: 'Pet Beds', discountPercentage: 8 }
]
}..
示例 3:具有多个条件和数组的 OR
查找符合以下任何条件的商店:销售电子产品、拥有高员工计数或具有特定的促销活动:
db.stores.find({
$or: [
{ "sales.salesByCategory.categoryName": { $in: ["Game Controllers", "Sound Bars", "Home Theater Projectors"] } },
{
$and: [
{ "staff.totalStaff.fullTime": { $gt: 10 } },
{ "staff.totalStaff.partTime": { $gt: 15 } }
]
},
{
"promotionEvents": {
$elemMatch: {
"eventName": "Super Sale Spectacular",
"discounts.discountPercentage": { $gt: 15 }
}
}
}
]
})
性能注意事项
- 独立计算数组中的每个
$or
条件 - 尽可能使用索引来提高性能
- 考虑最佳执行的条件顺序
-
$in
用于$or
同一字段的多个相等性检查 - 使条件数量
$or
保持合理