$filter - Amazon DocumentDB

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

$filter

Amazon DocumentDB 中的$filter运算符用于将筛选表达式应用于数组的每个元素,并返回一个仅包含符合指定条件的元素的数组。当您需要对文档中的数组字段执行复杂的筛选操作时,此运算符很有用。

参数

  • input: 要筛选的数组字段。

  • as:用于cond表达式中数组中每个input元素的变量名。

  • cond: 布尔表达式,用于确定是否应将给定元素包含在输出数组中。

示例(MongoDB 外壳)

以下示例演示如何使用$filter运算符来预测每个订单的客户,并创建一个新的数组字段 paidItems,其中仅包含价格大于 15 的 items 数组中的商品。从本质上讲,它会筛选每个订单的商品,仅包括价格超过15的产品。

创建示例文档

db.orders.insertMany([ { _id: 1, customer: "abc123", items: [ { name: "Product A", price: 10, qty: 2 }, { name: "Product B", price: 20, qty: 1 } ]}, { _id: 2, customer: "def456", items: [ { name: "Product C", price: 5, qty: 3 }, { name: "Product D", price: 15, qty: 4 } ]}, { _id: 3, customer: "ghi789", items: [ { name: "Product E", price: 8, qty: 3 }, { name: "Product F", price: 12, qty: 1 } ]} ]);

查询示例

db.orders.aggregate([ { $project: { customer: 1, paidItems: { $filter: { input: "$items", as: "item", cond: { $gt: ["$$item.price", 15] } } } } } ]).pretty();

输出

[ { _id: 1, customer: 'abc123', paidItems: [ { name: 'Product B', price: 20, qty: 1 } ] }, { _id: 2, customer: 'def456', paidItems: [] }, { _id: 3, customer: 'ghi789', paidItems: [] } ]

代码示例

要查看使用该$filter命令的代码示例,请选择要使用的语言的选项卡:

Node.js
const { MongoClient } = require('mongodb'); async function example() { const uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'; const client = new MongoClient(uri); try { await client.connect(); const db = client.db('test'); const collection = db.collection('orders'); const result = await collection.aggregate([ { $project: { customer: 1, paidItems: { $filter: { input: "$items", as: "item", cond: { $gt: ["$$item.price", 15] } } } } } ]).toArray(); console.log(JSON.stringify(result, null, 2)); } catch (error) { console.error('Error:', error); } finally { await client.close(); } } example();
Python
from pymongo import MongoClient from pprint import pprint def example(): uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false' with MongoClient(uri) as client: db = client.test collection = db.orders result = list(collection.aggregate([ { '$project': { 'customer': 1, 'paidItems': { '$filter': { 'input': '$items', 'as': 'item', 'cond': { '$gt': ['$$item.price', 15] } } } } } ])) for doc in result: pprint(doc) example()