$filter - Amazon DocumentDB

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

$filter

Amazon DocumentDB의 $filter 연산자는 배열의 각 요소에 필터 표현식을 적용하고 지정된 조건과 일치하는 요소만 포함하는 배열을 반환하는 데 사용됩니다. 이 연산자는 문서 내의 배열 필드에 대해 복잡한 필터링 작업을 수행해야 할 때 유용합니다.

파라미터

  • input: 필터링할 배열 필드입니다.

  • as: cond 표현식 내에서 input 배열의 각 요소에 사용할 변수 이름입니다.

  • cond: 지정된 요소를 출력 배열에 포함할지 여부를 결정하는 부울 표현식입니다.

예제(MongoDB 쉘)

다음 예제에서는 $filter 연산자를 사용하여 각 주문의 고객을 프로젝션하고 가격이 15보다 큰 항목 배열의 항목만 포함하는 새 배열 필드 paidItems를 생성하는 방법을 보여줍니다. 기본적으로 각 주문의 항목을 필터링하여 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()