View a markdown version of this page

$facet - Amazon DocumentDB

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

$facet

버전 8.0.2에서 새로 추가되었습니다.

Amazon DocumentDB의 $facet 집계 단계는 동일한 입력 문서 세트의 단일 단계 내에서 여러 집계 파이프라인을 처리합니다. 각 출력 필드는 자체 파이프라인을 정의하며 모든 파이프라인은 동일한 입력 문서를 수신합니다. 이를 통해 여러 개의 개별 쿼리를 통해 컬렉션을 실행하는 대신 단일 쿼리에서 개수, 그룹화 및 요약 통계와 같은 여러 개의 독립적인 집계를 계산할 수 있습니다.

각 하위 파이프라인은 독립적으로 실행되며 해당 출력 필드에 저장된 문서 배열을 생성합니다. 하위 파이프라인은 상태를 공유하지 않으므로 한 파이프라인의 출력은 다른 파이프라인에 영향을 주지 않습니다.

구문

{ $facet: { <outputField1>: [ <stage1>, <stage2>, ... ], <outputField2>: [ <stage1>, <stage2>, ... ], ... } }

파라미터

  • outputField (필수): 연결된 집계 파이프라인의 결과 배열을 포함하는 출력 필드의 이름입니다. 하나 이상의 출력 필드를 지정할 수 있습니다. 각 출력 필드는 입력 문서에 적용되는 집계 파이프라인 단계의 배열에 매핑됩니다.

출력

$facet 스테이지는 단일 문서를 반환합니다. 지정하는 각 출력 필드에는 해당 하위 파이프라인에서 생성된 문서 배열이 포함되어 있습니다.

제한 사항

  • $facet 하위 파이프라인에는 $changeStream, $collStats, $facet (중첩은 허용되지 않음), , $geoNear, $indexStats, $listSearchIndexes, $merge, $out, $planCacheStats, $search$searchMeta, 단계가 포함될 수 없습니다$vectorSearch.

  • $facet 스테이지가 반환하는 문서는 16MB BSON 문서 크기 제한 내에 있어야 합니다.

  • $sort 단계 앞에 오는 $facet 단계는 해당 순서를 $facet 경계 전체에 적용해야 하는 경우 $first, 또는 $bucketAuto 단계에서 주문에 민감한 누산기($last$push$firstN$lastN, $group, , $bucket, 또는 $mergeObjects)의 순서를 결정할 수 없습니다. 이는 그룹화 단계가 $facet 하위 파이프라인 내에 있는지 아니면 $facet 단계 뒤에 있는지에 관계없이 적용됩니다. 이 경우 Amazon DocumentDB는 파이프라인을 실행하는 대신 오류를 반환합니다. 이러한 누적기를 주문하려면 그룹화 $sort 단계 바로 앞에 $facet 있는 하위 파이프라인 내에 단계를 배치합니다. , $sum, 및 $min$max와 같은 주문 비구분 누적기는 영향을 받지 $count않습니다.

예제(MongoDB 쉘)

다음 예제에서는 $facet 스테이지를 사용하여 단일 쿼리에서 동일한 판매 데이터에 대해 여러 집계를 계산하는 방법을 보여줍니다.

샘플 문서 생성

db.sales.insertMany([ { item: "abc", price: 10, quantity: 2, date: new Date("2020-09-01") }, { item: "def", price: 20, quantity: 1, date: new Date("2020-10-01") }, { item: "ghi", price: 5, quantity: 3, date: new Date("2020-11-01") }, { item: "jkl", price: 15, quantity: 2, date: new Date("2020-12-01") }, { item: "abc", price: 25, quantity: 1, date: new Date("2021-01-01") } ]);

쿼리 예제

다음 명령은 $facet를 사용하여 단일 단계에서 항목당 판매된 총 수량, 전체 가격 통계 및 총 문서 수를 계산합니다.

db.sales.aggregate([ { $facet: { "totalByItem": [ { $group: { _id: "$item", totalQuantity: { $sum: "$quantity" } } } ], "priceStats": [ { $group: { _id: null, avgPrice: { $avg: "$price" }, maxPrice: { $max: "$price" } } } ], "documentCount": [ { $count: "total" } ] } } ])

출력

명령은 다음 출력을 반환합니다.

[ { totalByItem: [ { _id: "abc", totalQuantity: 3 }, { _id: "def", totalQuantity: 1 }, { _id: "ghi", totalQuantity: 3 }, { _id: "jkl", totalQuantity: 2 } ], priceStats: [ { _id: null, avgPrice: 15, maxPrice: 25 } ], documentCount: [ { total: 5 } ] } ]

코드 예제

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

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 sales = db.collection('sales'); const result = await sales.aggregate([ { $facet: { "totalByItem": [ { $group: { _id: "$item", totalQuantity: { $sum: "$quantity" } } } ], "priceStats": [ { $group: { _id: null, avgPrice: { $avg: "$price" }, maxPrice: { $max: "$price" } } } ], "documentCount": [ { $count: "total" } ] } } ]).toArray(); console.log(result); 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'] sales = db['sales'] result = list(sales.aggregate([ { '$facet': { 'totalByItem': [ {'$group': {'_id': '$item', 'totalQuantity': {'$sum': '$quantity'}}} ], 'priceStats': [ {'$group': {'_id': None, 'avgPrice': {'$avg': '$price'}, 'maxPrice': {'$max': '$price'}}} ], 'documentCount': [ {'$count': 'total'} ] } } ])) print(result) client.close() example()