$reduce - Amazon DocumentDB

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

$reduce

Amazon DocumentDB의 $reduce 집계 연산자는 배열의 요소에 두 인수의 함수를 누적하여 적용하여 배열을 단일 값으로 줄이는 데 사용됩니다. 이 연산자는 집계 파이프라인 내의 배열 데이터에 대해 복잡한 계산 또는 변환을 수행하는 데 특히 유용합니다.

파라미터

  • input: 축소할 배열입니다.

  • initialValue: 축소 작업에 사용할 초기 값입니다.

  • in: input 배열의 각 요소에 대해 평가할 표현식입니다. 이 표현식은 축소의 다음 반복에 사용할 값을 반환해야 합니다.

예제(MongoDB 쉘)

다음 예제에서는 $reduce 연산자를 사용하여 배열의 모든 요소 합계를 계산하는 방법을 보여줍니다.

샘플 문서 생성

db.orders.insertMany([ { "_id": 1, "items": [1, 2, 3, 4, 5] }, { "_id": 2, "items": [10, 20, 30] }, { "_id": 3, "items": [5, 15, 25, 35] }, { "_id": 4, "items": [100, 200] } ])

쿼리 예제

db.orders.aggregate([ { $project: { total: { $reduce: { input: "$items", initialValue: 0, in: { $add: ["$$value", "$$this"] } } } } } ])

출력

[ { "_id": 1, "total": 15 }, { "_id": 2, "total": 60 }, { "_id": 3, "total": 80 }, { "_id": 4, "total": 300 } ]

$reduce 연산자는 items 배열을 반복하여 각 요소를 0initialValue의에 추가합니다. 결과는 배열에 있는 모든 요소의 합계입니다.

코드 예제

$reduce 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

Node.js

다음은 Node.js 애플리케이션에서 $reduce 연산자를 사용하는 예입니다.

const { MongoClient } = require("mongodb"); async function main() { 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 orders = db.collection("orders"); const result = await orders.aggregate([ { $project: { total: { $reduce: { input: "$items", initialValue: 0, in: { $add: ["$$value", "$$this"] } } } } } ]).toArray(); console.log(result); await client.close(); } main();
Python

다음은 Python 애플리케이션에서 $reduce 연산자를 사용하는 예입니다.

from pymongo import MongoClient def main(): client = MongoClient("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false") db = client["test"] orders = db["orders"] result = list(orders.aggregate([ { "$project": { "total": { "$reduce": { "input": "$items", "initialValue": 0, "in": { "$add": ["$$value", "$$this"] } } } } } ])) print(result) client.close() if __name__ == "__main__": main()