$expr - Amazon DocumentDB
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

$expr

4.0 版的新增内容。

弹性集群不支持。

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

参数

  • expression:返回布尔值的表达式,允许您对文档字段执行比较和计算。

示例(MongoDB 外壳)

以下示例演示如何使用$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()