$switch - Amazon DocumentDB

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

$switch

4.0 版的新功能。

Elastic 叢集不支援。

$switch 運算子是 Amazon DocumentDB 中的條件式表達式運算子,可讓您評估案例表達式清單,並傳回評估為 true 的第一個案例的值,如果沒有案例表達式為 true,則傳回預設值。

參數

  • branches:文件陣列,每個文件都有一個案例欄位,其中包含要評估的布林表達式,以及一個接著欄位,其中包含案例表達式為 true 時要傳回的值。

  • default:(選用) 如果沒有任何案例表達式為 true 時要傳回的值。

範例 (MongoDB Shell)

下列範例示範如何使用 $switch運算子,根據訂單總計來判斷訂單的運送成本。

建立範例文件

db.orders.insertMany([ { _id: 1, total: 50 }, { _id: 2, total: 150 }, { _id: 3, total: 250 } ]);

查詢範例

db.orders.aggregate([ { $project: { _id: 1, total: 1, shippingCost: { $switch: { branches: [ { case: { $lte: ["$total", 100] }, then: 5 }, { case: { $lte: ["$total", 200] }, then: 10 }, { case: { $gt: ["$total", 200] }, then: 15 } ], default: 0 } } } } ])

輸出

[ { "_id": 1, "total": 50, "shippingCost": 5 }, { "_id": 2, "total": 150, "shippingCost": 10 }, { "_id": 3, "total": 250, "shippingCost": 15 } ]

程式碼範例

若要檢視使用 $switch命令的程式碼範例,請選擇您要使用的語言標籤:

Node.js
const { MongoClient } = require('mongodb'); async function main() { 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 collection = db.collection('orders'); const result = await collection.aggregate([ { $project: { _id: 1, total: 1, shippingCost: { $switch: { branches: [ { case: { $lte: ['$total', 100] }, then: 5 }, { case: { $lte: ['$total', 200] }, then: 10 }, { case: { $gt: ['$total', 200] }, then: 15 } ], default: 0 } } } } ]).toArray(); console.log(result); await client.close(); } main();
Python
from pymongo import MongoClient def main(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client.test collection = db.orders result = list(collection.aggregate([ { '$project': { '_id': 1, 'total': 1, 'shippingCost': { '$switch': { 'branches': [ { 'case': { '$lte': ['$total', 100] }, 'then': 5 }, { 'case': { '$lte': ['$total', 200] }, 'then': 10 }, { 'case': { '$gt': ['$total', 200] }, 'then': 15 } ], 'default': 0 } } } } ])) print(result) client.close() if __name__ == '__main__': main()