本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$expr
4.0 版的新功能。
Elastic 叢集不支援。
Amazon DocumentDB 中的$expr運算子可讓您在查詢語言中使用彙總表達式。它可讓您對文件中的欄位執行複雜的比較和運算,類似於您使用彙總管道階段的方式。
參數
範例 (MongoDB Shell)
下列範例示範如何使用 $expr運算子來尋找 manufacturingCost 欄位大於 price 欄位的所有文件。
建立範例文件
db.inventory.insertMany([
{ item: "abc", manufacturingCost: 500, price: 100 },
{ item: "def", manufacturingCost: 300, price: 450 },
{ item: "ghi", manufacturingCost: 400, price: 120 }
]);
查詢範例
db.inventory.find({
$expr: {
$gt: ["$manufacturingCost", "$price"]
}
})
輸出
{ "_id" : ObjectId("60b9d4d68d2cac581bc5a89a"), "item" : "abc", "manufacturingCost" : 500, "price" : 100 },
{ "_id" : ObjectId("60b9d4d68d2cac581bc5a89c"), "item" : "ghi", "manufacturingCost" : 400, "price" : 120 }
程式碼範例
若要檢視使用 $expr命令的程式碼範例,請選擇您要使用的語言標籤:
- 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('inventory');
const result = await collection.find({
$expr: {
$gt: ['$manufacturingCost', '$price']
}
}).toArray();
console.log(result);
await 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['inventory']
result = list(collection.find({
'$expr': {
'$gt': ['$manufacturingCost', '$price']
}
}))
print(result)
client.close()
example()