View a markdown version of this page

$expr - Amazon DocumentDB

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

$expr

4.0 版的新功能。

Elastic 叢集不支援。

Amazon DocumentDB 中的$expr運算子可讓您在查詢語言中使用彙總表達式。它可讓您對文件中的欄位執行複雜的比較和運算,類似於您使用彙總管道階段的方式。

置放在 運算子中的 $eq、$gt、、 $lt $lte和 $gte比較$expr運算子可以使用索引,包括在$lookup階段中參考的from集合上的索引。

限制

  • 索引只能用於欄位和常數之間的比較,因此運算元必須解析為常數。例如, $a與常數值之間的比較可以使用 索引,但 $a與 之間的比較$b無法。

  • 不會使用多金鑰、部分或稀疏索引。在這些情況下,查詢會回到集合掃描。

  • 當let運算元解析為空值或遺失值時,比較無法使用目標索引搜尋。在此情況下,Amazon DocumentDB 會執行完整的索引掃描。

參數

  • expression:傳回布林值的表達式,可讓您對文件欄位執行比較和運算。

範例 (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()