$or - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$or

$or 運算子用於在兩個或多個表達式的陣列上執行邏輯 OR 操作。它會傳回至少符合其中一個表達式的文件。當您需要查詢符合任何一種條件的文件時,此運算子非常有用。

參數

  • expression1:要評估的第一個表達式。

  • expression2:要評估的第二個表達式。

  • ...:要評估的其他表達式 (選用)。

範例 (MongoDB Shell)

下列範例示範 $or運算子的用法,以尋找 make為 "TruckForYou" 且模型為 "Heavy H1" 或 "SportForYou" 且模型為 "Bolid 1" 的文件。

建立範例文件

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()