本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$cond
Amazon DocumentDB 中的$cond运算符用于计算条件表达式并返回两个可能的结果表达式之一。
参数
-
if: 要计算的布尔表达式。
-
then:如果表达式为真则返回的if表达式。
-
else:如果表达式为假则返回的if表达式。
示例(MongoDB 外壳)
以下示例演示如何使用$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()