View a markdown version of this page

$expr - Amazon DocumentDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$expr

4.0 版中的新增内容。

弹性集群不支持。

Amazon DocumentDB 中的$expr运算符允许您在查询语言中使用聚合表达式。它使您能够对文档中的字段进行复杂的比较和计算,类似于使用聚合管道阶段的方式。

放置在运算符中的$eq$lt$lte$gt、、、和$gte比较$expr运算符可以使用索引,包括$lookup阶段中引用的from集合的索引。

限制

  • 索引只能用于字段和常量之间的比较,因此操作数必须解析为常量。例如,与$a常量值的比较可以使用索引,但$a和之间的比较$b不能。

  • 不使用多键、部分或稀疏索引。在这种情况下,查询会退回到集合扫描。

  • 当let操作数解析为空值或缺失值时,比较不能使用目标索引查找。在这种情况下,亚马逊 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()