$cond - Amazon DocumentDB

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

$cond

Amazon DocumentDB 中的$cond運算子用於評估條件式表達式,並傳回兩個可能的結果表達式之一。

參數

  • if:要評估的布林表達式。

  • then:如果表達式為 true,則傳回的if表達式。

  • else:如果表達式為 false,則傳回的if表達式。

範例 (MongoDB Shell)

下列範例示範如何使用 $cond運算子,根據一個人的年齡傳回值。

建立範例文件

db.people.insertMany([ { _id: 1, name: "John Doe", age: 35 }, { _id: 2, name: "Jane Doe", age: 25 }, { _id: 3, name: "Bob Smith", age: 65 } ]);

查詢範例

db.people.aggregate([ { $project: { name: 1, ageGroup: { $cond: { if: { $lt: ["$age", 30] }, then: "young", else: { $cond: { if: { $lt: ["$age", 65] }, then: "middle-aged", else: "elderly" } } } } } } ])

輸出

[ { "_id" : 1, "name" : "John Doe", "ageGroup" : "middle-aged" }, { "_id" : 2, "name" : "Jane Doe", "ageGroup" : "young" }, { "_id" : 3, "name" : "Bob Smith", "ageGroup" : "elderly" } ]

程式碼範例

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

Node.js
const { MongoClient } = require('mongodb'); async function example() { 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('people'); const result = await collection.aggregate([ { $project: { name: 1, ageGroup: { $cond: { if: { $lt: ["$age", 30] }, then: "young", else: { $cond: { if: { $lt: ["$age", 65] }, then: "middle-aged", else: "elderly" } } } } } } ]).toArray(); console.log(result); client.close(); } example();
Python
from pymongo import MongoClient def example(): 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.people result = list(collection.aggregate([ { '$project': { 'name': 1, 'ageGroup': { '$cond': { 'if': { '$lt': ["$age", 30]}, 'then': "young", 'else': { '$cond': { 'if': { '$lt': ["$age", 65]}, 'then': "middle-aged", 'else': "elderly" } } } } } } ])) print(result) client.close() example()