本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$switch
4.0 版的新增内容。
弹性集群不支持。
$switch运算符是 Amazon DocumentDB 中的条件表达式运算符,它允许您评估案例表达式列表并返回计算结果为 true 的第一个案例的值,如果没有大小写表达式为真,则返回默认值。
参数
示例(MongoDB 外壳)
以下示例演示如何使用$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()