Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$or
该$or运算符用于对包含两个或更多表达式的数组执行逻辑 OR 运算。它返回至少与其中一个表达式匹配的文档。当您需要查询满足多个条件中任意一个的文档时,此运算符很有用。
参数
-
expression1:要计算的第一个表达式。
-
expression2:要计算的第二个表达式。
-
...:要评估的其他表达式(可选)。
示例(MongoDB 外壳)
以下示例演示了如何使用$or运算符来查找文档,其中模型为 “H make eavy H1TruckForYou” 时为 “”,或者模型为 “Bolid 1SportForYou” 时为 “”。
创建示例文档
db.cars.insertMany([
{ make: "TruckForYou", model: "Heavy H1", year: 2020 },
{ make: "SportForYou", model: "Bolid 1", year: 2021 },
{ make: "TruckForYou", model: "Cargo 5", year: 2019 },
{ make: "SportForYou", model: "Racer 2", year: 2022 }
]);
查询示例
db.cars.find({
$or: [
{ make: "TruckForYou", model: "Heavy H1" },
{ make: "SportForYou", model: "Bolid 1" }
]
});
输出
[
{
_id: ObjectId('...'),
make: 'TruckForYou',
model: 'Heavy H1',
year: 2020
},
{
_id: ObjectId('...'),
make: 'SportForYou',
model: 'Bolid 1',
year: 2021
}
]
代码示例
要查看使用该$or命令的代码示例,请选择要使用的语言的选项卡:
- Node.js
-
const { MongoClient } = require('mongodb');
async function findCarsByMakeModel() {
const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
const db = client.db('test');
const cars = db.collection('cars');
const result = await cars.find({
$or: [
{ make: "TruckForYou", model: "Heavy H1" },
{ make: "SportForYou", model: "Bolid 1" }
]
}).toArray();
console.log(result);
client.close();
}
findCarsByMakeModel();
- Python
-
from pymongo import MongoClient
def find_cars_by_make_model():
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
cars = db.cars
result = list(cars.find({
'$or': [
{'make': 'TruckForYou', 'model': 'Heavy H1'},
{'make': 'SportForYou', 'model': 'Bolid 1'}
]
}))
print(result)
client.close()
find_cars_by_make_model()