本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$let
Amazon DocumentDB 中的$let運算子用於將變數繫結至值,並在運算式中使用這些變數。它可讓您定義可在彙總管道相同階段內後續表達式中使用的本機變數。
參數
-
vars:定義要在表達式中使用的變數的物件。
-
in:使用 vars 參數中定義的變數的表達式。
範例 (MongoDB Shell)
此範例示範運算$let子用來計算矩形的區域。
建立範例文件
db.shapes.insertMany([
{ name: "Rectangle 1", length: 5, width: 3 },
{ name: "Rectangle 2", length: 7, width: 4 },
{ name: "Rectangle 3", length: 6, width: 2 }
]);
查詢範例
db.shapes.aggregate([
{
$project: {
name: 1,
area: {
$let: {
vars: {
length: "$length",
width: "$width"
},
in: {
$multiply: ["$$length", "$$width"]
}
}
}
}
}
])
輸出
[
{
"_id": ObjectId("6161e5b1a3eba3c7f2960d03"),
"name": "Rectangle 1",
"area": 15
},
{
"_id": ObjectId("6161e5b1a3eba3c7f2960d04"),
"name": "Rectangle 2",
"area": 28
},
{
"_id": ObjectId("6161e5b1a3eba3c7f2960d05"),
"name": "Rectangle 3",
"area": 12
}
]
程式碼範例
若要檢視使用 $let命令的程式碼範例,請選擇您要使用的語言標籤:
- Node.js
-
const { MongoClient } = require('mongodb');
async function calculateRectangleAreas() {
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('shapes');
const result = await shapes.aggregate([
{
$project: {
name: 1,
area: {
$let: {
vars: {
length: '$length',
width: '$width'
},
in: {
$multiply: ['$$length', '$$width']
}
}
}
}
}
]).toArray();
console.log(result);
client.close();
}
calculateRectangleAreas();
- Python
-
from pymongo import MongoClient
def calculate_rectangle_areas():
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.shapes
result = list(shapes.aggregate([
{
'$project': {
'name': 1,
'area': {
'$let': {
'vars': {
'length': '$length',
'width': '$width'
},
'in': {
'$multiply': ['$$length', '$$width']
}
}
}
}
}
]))
print(result)
client.close()
calculate_rectangle_areas()