Docs Menu
Docs Home
/
데이터베이스 매뉴얼
/ / /

배열 해제 및 데이터 그룹화

이 튜토리얼에서는 집계 파이프라인 구성하고, 컬렉션 에서 집계 수행하고, 선택한 언어 사용하여 결과를 표시하는 방법을 보여 줍니다.

이 튜토리얼에서는 고객 주문 데이터에서 인사이트를 생성하는 방법을 보여줍니다. 결과에는 비용 $15 이상인 주문한 제품 목록이 표시됩니다. 각 문서 에는 판매된 단위 수와 각 제품의 총 판매 금액이 포함되어 있습니다.

집계 파이프라인 다음 작업을 수행합니다.

  • 배열 필드를 별도의 문서로 풀기

  • 문서의 하위 집합을 필드 값으로 일치

  • 공통 필드 값을 기준으로 문서 그룹화

  • 각 결과 문서에 계산된 필드를 추가합니다.


오른쪽 상단의 언어 선택 드롭다운 메뉴를 사용하여 다음 예제의 언어 설정하다 하거나 MongoDB Shell 선택합니다.


이 예시 제품 주문을 설명하는 문서가 포함된 orders 컬렉션 사용합니다. 각 주문에는 여러 제품이 포함되어 있으므로 집계 의 첫 번째 단계에서는 제품 배열 개별 제품 주문 문서로 압축을 풉니다.

컬렉션 만들려면 메서드를 사용합니다.orders insertMany()

db.orders.deleteMany({})
db.orders.insertMany( [
{
order_id: 6363763262239,
products: [
{
prod_id: "abc12345",
name: "Asus Laptop",
price: 431
},
{
prod_id: "def45678",
name: "Karcher Hose Set",
price: 22
}
]
},
{
order_id: 1197372932325,
products: [
{
prod_id: "abc12345",
name: "Asus Laptop",
price: 429
}
]
},
{
order_id: 9812343774839,
products: [
{
prod_id: "pqr88223",
name: "Morphy Richards Food Mixer",
price: 431
},
{
prod_id: "def45678",
name: "Karcher Hose Set",
price: 21
}
]
},
{
order_id: 4433997244387,
products: [
{
prod_id: "def45678",
name: "Karcher Hose Set",
price: 23
},
{
prod_id: "jkl77336",
name: "Picky Pencil Sharpener",
price: 1
},
{
prod_id: "xyz11228",
name: "Russell Hobbs Chrome Kettle",
price: 16
}
]
}
] )

이 집계 튜토리얼을 시작하기 전에 새 C 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

운전자 설치하고 MongoDB 에 연결하는 방법을 학습 C 드라이버 시작하기 가이드 참조하세요.

C 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드 참조하세요.

운전자 설치한 후 agg-tutorial.c라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

#include <stdio.h>
#include <bson/bson.h>
#include <mongoc/mongoc.h>
int main(void)
{
mongoc_init();
// Replace the placeholder with your connection string.
char *uri = "<connection string>";
mongoc_client_t* client = mongoc_client_new(uri);
// Get a reference to relevant collections.
// ... mongoc_collection_t *some_coll = mongoc_client_get_collection(client, "agg_tutorials_db", "some_coll");
// ... mongoc_collection_t *another_coll = mongoc_client_get_collection(client, "agg_tutorials_db", "another_coll");
// Delete any existing documents in collections if needed.
// ... {
// ... bson_t *filter = bson_new();
// ... bson_error_t error;
// ... if (!mongoc_collection_delete_many(some_coll, filter, NULL, NULL, &error))
// ... {
// ... fprintf(stderr, "Delete error: %s\n", error.message);
// ... }
// ... bson_destroy(filter);
// ... }
// Insert sample data into the collection or collections.
// ... {
// ... size_t num_docs = ...;
// ... bson_t *docs[num_docs];
// ...
// ... docs[0] = ...;
// ...
// ... bson_error_t error;
// ... if (!mongoc_collection_insert_many(some_coll, (const bson_t **)docs, num_docs, NULL, NULL, &error))
// ... {
// ... fprintf(stderr, "Insert error: %s\n", error.message);
// ... }
// ...
// ... for (int i = 0; i < num_docs; i++)
// ... {
// ... bson_destroy(docs[i]);
// ... }
// ... }
{
const bson_t *doc;
// Add code to create pipeline stages.
bson_t *pipeline = BCON_NEW("pipeline", "[",
// ... Add pipeline stages here.
"]");
// Run the aggregation.
// ... mongoc_cursor_t *results = mongoc_collection_aggregate(some_coll, MONGOC_QUERY_NONE, pipeline, NULL, NULL);
bson_destroy(pipeline);
// Print the aggregation results.
while (mongoc_cursor_next(results, &doc))
{
char *str = bson_as_canonical_extended_json(doc, NULL);
printf("%s\n", str);
bson_free(str);
}
bson_error_t error;
if (mongoc_cursor_error(results, &error))
{
fprintf(stderr, "Aggregation error: %s\n", error.message);
}
mongoc_cursor_destroy(results);
}
// Clean up resources.
// ... mongoc_collection_destroy(some_coll);
mongoc_client_destroy(client);
mongoc_cleanup();
return EXIT_SUCCESS;
}

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포의 연결 문자열 찾는 방법을 학습 C 시작하기 가이드 의 연결 문자열 만들기 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

char *uri = "mongodb+srv://mongodb-example:27017";

이 예시 제품 주문을 설명하는 문서가 포함된 orders 컬렉션 사용합니다. 각 주문에는 여러 제품이 포함되어 있으므로 집계 의 첫 번째 단계에서는 제품 배열 개별 제품 주문 문서로 압축을 풉니다.

orders 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

mongoc_collection_t *orders = mongoc_client_get_collection(client, "agg_tutorials_db", "orders");
{
bson_t *filter = bson_new();
bson_error_t error;
if (!mongoc_collection_delete_many(orders, filter, NULL, NULL, &error))
{
fprintf(stderr, "Delete error: %s\n", error.message);
}
bson_destroy(filter);
}
{
size_t num_docs = 4;
bson_t *docs[num_docs];
docs[0] = BCON_NEW(
"order_id", BCON_INT64(6363763262239),
"products", "[",
"{",
"prod_id", BCON_UTF8("abc12345"),
"name", BCON_UTF8("Asus Laptop"),
"price", BCON_INT32(431),
"}",
"{",
"prod_id", BCON_UTF8("def45678"),
"name", BCON_UTF8("Karcher Hose Set"),
"price", BCON_INT32(22),
"}",
"]");
docs[1] = BCON_NEW(
"order_id", BCON_INT64(1197372932325),
"products", "[",
"{",
"prod_id", BCON_UTF8("abc12345"),
"name", BCON_UTF8("Asus Laptop"),
"price", BCON_INT32(429),
"}",
"]");
docs[2] = BCON_NEW(
"order_id", BCON_INT64(9812343774839),
"products", "[",
"{",
"prod_id", BCON_UTF8("pqr88223"),
"name", BCON_UTF8("Morphy Richards Food Mixer"),
"price", BCON_INT32(431),
"}",
"{",
"prod_id", BCON_UTF8("def45678"),
"name", BCON_UTF8("Karcher Hose Set"),
"price", BCON_INT32(21),
"}",
"]");
docs[3] = BCON_NEW(
"order_id", BCON_INT64(4433997244387),
"products", "[",
"{",
"prod_id", BCON_UTF8("def45678"),
"name", BCON_UTF8("Karcher Hose Set"),
"price", BCON_INT32(23),
"}",
"{",
"prod_id", BCON_UTF8("jkl77336"),
"name", BCON_UTF8("Picky Pencil Sharpener"),
"price", BCON_INT32(1),
"}",
"{",
"prod_id", BCON_UTF8("xyz11228"),
"name", BCON_UTF8("Russell Hobbs Chrome Kettle"),
"price", BCON_INT32(16),
"}",
"]");
bson_error_t error;
if (!mongoc_collection_insert_many(orders, (const bson_t **)docs, num_docs, NULL, NULL, &error))
{
fprintf(stderr, "Insert error: %s\n", error.message);
}
for (int i = 0; i < num_docs; i++)
{
bson_destroy(docs[i]);
}
}

집계 튜토리얼을 따라 하기 전에 새 C++ 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

운전자 설치하고 MongoDB 에 연결하는 방법을 학습 C++ 시작하기 튜토리얼을 참조하세요.

C++ 운전자 사용에 대해 자세히 학습 API 설명서를 참조하세요.

C++ 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드 참조하세요.

운전자 설치한 후 agg-tutorial.cpp라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

#include <iostream>
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/basic/kvp.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/pipeline.hpp>
#include <mongocxx/uri.hpp>
#include <chrono>
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;
using bsoncxx::builder::basic::make_array;
int main() {
mongocxx::instance instance;
// Replace the placeholder with your connection string.
mongocxx::uri uri("<connection string>");
mongocxx::client client(uri);
auto db = client["agg_tutorials_db"];
// Delete existing data in the database, if necessary.
db.drop();
// Get a reference to relevant collections.
// ... auto some_coll = db["..."];
// ... auto another_coll = db["..."];
// Insert sample data into the collection or collections.
// ... some_coll.insert_many(docs);
// Create an empty pipelne.
mongocxx::pipeline pipeline;
// Add code to create pipeline stages.
// pipeline.match(make_document(...));
// Run the aggregation and print the results.
auto cursor = orders.aggregate(pipeline);
for (auto&& doc : cursor) {
std::cout << bsoncxx::to_json(doc, bsoncxx::ExtendedJsonMode::k_relaxed) << std::endl;
}
}

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포의 연결 문자열 찾는 방법을 학습 C++ 시작하기 튜토리얼의 연결 문자열 만들기 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

mongocxx::uri uri{"mongodb+srv://mongodb-example:27017"};

이 예시 제품 주문을 설명하는 문서가 포함된 orders 컬렉션 사용합니다. 각 주문에는 여러 제품이 포함되어 있으므로 집계 의 첫 번째 단계에서는 제품 배열 개별 제품 주문 문서로 압축을 풉니다.

orders 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

auto orders = db["orders"];
std::vector<bsoncxx::document::value> order_docs = {
bsoncxx::from_json(R"({
"order_id": 6363763262239,
"products": [
{
"prod_id": "abc12345",
"name": "Asus Laptop",
"price": 431
},
{
"prod_id": "def45678",
"name": "Karcher Hose Set",
"price": 22
}
]
})"),
bsoncxx::from_json(R"({
"order_id": 1197372932325,
"products": [
{
"prod_id": "abc12345",
"name": "Asus Laptop",
"price": 429
}
]
})"),
bsoncxx::from_json(R"({
"order_id": 9812343774839,
"products": [
{
"prod_id": "pqr88223",
"name": "Morphy Richards Food Mixer",
"price": 431
},
{
"prod_id": "def45678",
"name": "Karcher Hose Set",
"price": 21
}
]
})"),
bsoncxx::from_json(R"({
"order_id": 4433997244387,
"products": [
{
"prod_id": "def45678",
"name": "Karcher Hose Set",
"price": 23
},
{
"prod_id": "jkl77336",
"name": "Picky Pencil Sharpener",
"price": 1
},
{
"prod_id": "xyz11228",
"name": "Russell Hobbs Chrome Kettle",
"price": 16
}
]
})")
};
orders.insert_many(order_docs); // Might throw an exception

이 집계 튜토리얼을 시작하기 전에 새 C#/ .NET 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

운전자 설치하고 MongoDB 에 연결하는 방법을 학습 C#/ .NET 드라이버 빠른 시작 가이드 참조하세요.

C#/ .NET 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드 참조하세요.

운전자 설치한 후 다음 코드를 Program.cs 파일 에 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
// Define data model classes.
// ... public class MyClass { ... }
// Replace the placeholder with your connection string.
var uri = "<connection string>";
var client = new MongoClient(uri);
var aggDB = client.GetDatabase("agg_tutorials_db");
// Get a reference to relevant collections.
// ... var someColl = aggDB.GetCollection<MyClass>("someColl");
// ... var anotherColl = aggDB.GetCollection<MyClass>("anotherColl");
// Delete any existing documents in collections if needed.
// ... someColl.DeleteMany(Builders<MyClass>.Filter.Empty);
// Insert sample data into the collection or collections.
// ... someColl.InsertMany(new List<MyClass> { ... });
// Add code to chain pipeline stages to the Aggregate() method.
// ... var results = someColl.Aggregate().Match(...);
// Print the aggregation results.
foreach (var result in results.ToList())
{
Console.WriteLine(result);
}

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포의 연결 문자열 찾는 방법을 학습 C# 빠른 시작 가이드 의 Atlas 에서 무료 계층 클러스터 설정 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

var uri = "mongodb+srv://mongodb-example:27017";

이 예시 제품 주문을 설명하는 문서가 포함된 orders 컬렉션 사용합니다. 각 주문에는 여러 제품이 포함되어 있으므로 집계 의 첫 번째 단계에서는 제품 배열 개별 제품 주문 문서로 압축을 풉니다.

먼저 C# 클래스를 만들어 orders 컬렉션 의 데이터를 모델링합니다.

public class Order
{
[BsonId]
public ObjectId Id { get; set; }
public long OrderId { get; set; }
public List<Product> Products { get; set; }
}
public class OrderUnwound
{
public long OrderId { get; set; }
public Product Products { get; set; }
}
public class Product
{
public string ProductId { get; set; }
public string Name { get; set; }
public int Price { get; set; }
}

orders 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

var orders = aggDB.GetCollection<Order>("orders");
orders.DeleteMany(Builders<Order>.Filter.Empty);
orders.InsertMany(new List<Order>
{
new Order
{
OrderId = 6363763262239L,
Products = new List<Product>
{
new Product
{
ProductId = "abc12345",
Name = "Asus Laptop",
Price = 431
},
new Product
{
ProductId = "def45678",
Name = "Karcher Hose Set",
Price = 22
}
}
},
new Order
{
OrderId = 1197372932325L,
Products = new List<Product>
{
new Product
{
ProductId = "abc12345",
Name = "Asus Laptop",
Price = 429
}
}
},
new Order
{
OrderId = 9812343774839L,
Products = new List<Product>
{
new Product
{
ProductId = "pqr88223",
Name = "Morphy Richards Food Mixer",
Price = 431
},
new Product
{
ProductId = "def45678",
Name = "Karcher Hose Set",
Price = 21
}
}
},
new Order
{
OrderId = 4433997244387L,
Products = new List<Product>
{
new Product
{
ProductId = "def45678",
Name = "Karcher Hose Set",
Price = 23
},
new Product
{
ProductId = "jkl77336",
Name = "Picky Pencil Sharpener",
Price = 1
},
new Product
{
ProductId = "xyz11228",
Name = "Russell Hobbs Chrome Kettle",
Price = 16
}
}
}
});

이 집계 튜토리얼을 시작하기 전에 새 고 (Go) 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

운전자 설치하고 MongoDB 에 연결하는 방법을 학습 고 (Go) 드라이버 빠른 시작 가이드 참조하세요.

고 (Go) 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드 참조하세요.

운전자 설치한 후 agg_tutorial.go라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

package main
import (
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
// Define structs.
// type MyStruct struct { ... }
func main() {
// Replace the placeholder with your connection string.
const uri = "<connection string>"
client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
log.Fatal(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
log.Fatal(err)
}
}()
aggDB := client.Database("agg_tutorials_db")
// Get a reference to relevant collections.
// ... someColl := aggDB.Collection("...")
// ... anotherColl := aggDB.Collection("...")
// Delete any existing documents in collections if needed.
// ... someColl.DeleteMany(context.TODO(), bson.D{})
// Insert sample data into the collection or collections.
// ... _, err = someColl.InsertMany(...)
// Add code to create pipeline stages.
// ... myStage := bson.D{{...}}
// Create a pipeline that includes the stages.
// ... pipeline := mongo.Pipeline{...}
// Run the aggregation.
// ... cursor, err := someColl.Aggregate(context.TODO(), pipeline)
if err != nil {
log.Fatal(err)
}
defer func() {
if err := cursor.Close(context.TODO()); err != nil {
log.Fatalf("failed to close cursor: %v", err)
}
}()
// Decode the aggregation results.
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
log.Fatalf("failed to decode results: %v", err)
}
// Print the aggregation results.
for _, result := range results {
res, _ := bson.MarshalExtJSON(result, false, false)
fmt.Println(string(res))
}
}

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포서버의 연결 문자열 찾는 방법을 학습 고 (Go) 빠른 시작 가이드 의 MongoDB 클러스터 만들기 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

const uri = "mongodb+srv://mongodb-example:27017";

이 예시 제품 주문을 설명하는 문서가 포함된 orders 컬렉션 사용합니다. 각 주문에는 여러 제품이 포함되어 있으므로 집계 의 첫 번째 단계에서는 제품 배열 개별 제품 주문 문서로 압축을 풉니다.

먼저 고 (Go) 구조체를 만들어 orders 컬렉션 의 데이터를 모델링합니다.

type Order struct {
OrderID int `bson:"order_id"`
Products []Product `bson:"products"`
}
type Product struct {
ProductID string `bson:"prod_id"`
Name string `bson:"name"`
Price int `bson:"price"`
}

orders 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

orders := aggDB.Collection("orders")
orders.DeleteMany(context.TODO(), bson.D{})
_, err = orders.InsertMany(context.TODO(), []interface{}{
Order{
OrderID: 6363763262239,
Products: []Product{
{ProductID: "abc12345", Name: "Asus Laptop", Price: 431},
{ProductID: "def45678", Name: "Karcher Hose Set", Price: 22},
},
},
Order{
OrderID: 1197372932325,
Products: []Product{
{ProductID: "abc12345", Name: "Asus Laptop", Price: 429},
},
},
Order{
OrderID: 9812343774839,
Products: []Product{
{ProductID: "pqr88223", Name: "Morphy Richards Food Mixer", Price: 431},
{ProductID: "def45678", Name: "Karcher Hose Set", Price: 21},
},
},
Order{
OrderID: 4433997244387,
Products: []Product{
{ProductID: "def45678", Name: "Karcher Hose Set", Price: 23},
{ProductID: "jkl77336", Name: "Picky Pencil Sharpene", Price: 1},
{ProductID: "xyz11228", Name: "Russell Hobbs Chrome Kettle", Price: 16},
},
},
})
if err != nil {
log.Fatal(err)
}

집계 튜토리얼을 시작하기 전에 새 Java 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

운전자 설치하고 MongoDB 에 연결하는 방법을 학습 Java 드라이버 시작하기 가이드 참조하세요.

Java Sync 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드 참조하세요.

운전자 설치한 후 AggTutorial.java라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

package org.example;
// Modify imports for each tutorial as needed.
import com.mongodb.client.*;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Sorts;
import org.bson.Document;
import org.bson.conversions.Bson;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AggTutorial {
public static void main( String[] args ) {
// Replace the placeholder with your connection string.
String uri = "<connection string>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase aggDB = mongoClient.getDatabase("agg_tutorials_db");
// Get a reference to relevant collections.
// ... MongoCollection<Document> someColl = ...
// ... MongoCollection<Document> anotherColl = ...
// Delete any existing documents in collections if needed.
// ... someColl.deleteMany(Filters.empty());
// Insert sample data into the collection or collections.
// ... someColl.insertMany(...);
// Create an empty pipeline array.
List<Bson> pipeline = new ArrayList<>();
// Add code to create pipeline stages.
// ... pipeline.add(...);
// Run the aggregation.
// ... AggregateIterable<Document> aggregationResult = someColl.aggregate(pipeline);
// Print the aggregation results.
for (Document document : aggregationResult) {
System.out.println(document.toJson());
}
}
}
}

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포의 연결 문자열 찾는 방법을 학습 Java Sync 빠른 시작 가이드 의 연결 문자열 만들기 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

String uri = "mongodb+srv://mongodb-example:27017";

이 예시 제품 주문을 설명하는 문서가 포함된 orders 컬렉션 사용합니다. 각 주문에는 여러 제품이 포함되어 있으므로 집계 의 첫 번째 단계에서는 제품 배열 개별 제품 주문 문서로 압축을 풉니다.

orders 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

MongoCollection<Document> orders = aggDB.getCollection("orders");
orders.deleteMany(Filters.empty());
orders.insertMany(
Arrays.asList(
new Document("order_id", 6363763262239f)
.append("products", Arrays.asList(
new Document("prod_id", "abc12345")
.append("name", "Asus Laptop")
.append("price", 431),
new Document("prod_id", "def45678")
.append("name", "Karcher Hose Set")
.append("price", 22)
)),
new Document("order_id", 1197372932325f)
.append("products", Collections.singletonList(
new Document("prod_id", "abc12345")
.append("name", "Asus Laptop")
.append("price", 429)
)),
new Document("order_id", 9812343774839f)
.append("products", Arrays.asList(
new Document("prod_id", "pqr88223")
.append("name", "Morphy Richards Food Mixer")
.append("price", 431),
new Document("prod_id", "def45678")
.append("name", "Karcher Hose Set")
.append("price", 21)
)),
new Document("order_id", 4433997244387f)
.append("products", Arrays.asList(
new Document("prod_id", "def45678")
.append("name", "Karcher Hose Set")
.append("price", 23),
new Document("prod_id", "jkl77336")
.append("name", "Picky Pencil Sharpener")
.append("price", 1),
new Document("prod_id", "xyz11228")
.append("name", "Russell Hobbs Chrome Kettle")
.append("price", 16)
))
)
);

집계 튜토리얼을 시작하기 전에 새 코틀린 (Kotlin) 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

운전자 설치하고 MongoDB 에 연결하는 방법을 학습 코틀린 (Kotlin) ) 드라이버 빠른 시작 가이드 참조하세요.

코틀린 (Kotlin) ) 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드 참조하세요.

운전자 외에도 build.gradle.kts 파일 에 다음 종속성을 추가하고 프로젝트 다시 로드해야 합니다.

dependencies {
// Implements Kotlin serialization
implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:1.5.1")
// Implements Kotlin date and time handling
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.6.1")
}

운전자 설치한 후 AggTutorial.kt라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

package org.example
// Modify imports for each tutorial as needed.
import com.mongodb.client.model.*
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.toJavaLocalDateTime
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import org.bson.Document
import org.bson.conversions.Bson
// Define data classes.
@Serializable
data class MyClass(
...
)
suspend fun main() {
// Replace the placeholder with your connection string.
val uri = "<connection string>"
MongoClient.create(uri).use { mongoClient ->
val aggDB = mongoClient.getDatabase("agg_tutorials_db")
// Get a reference to relevant collections.
// ... val someColl = ...
// Delete any existing documents in collections if needed.
// ... someColl.deleteMany(empty())
// Insert sample data into the collection or collections.
// ... someColl.insertMany( ... )
// Create an empty pipeline.
val pipeline = mutableListOf<Bson>()
// Add code to create pipeline stages.
// ... pipeline.add(...)
// Run the aggregation.
// ... val aggregationResult = someColl.aggregate<Document>(pipeline)
// Print the aggregation results.
aggregationResult.collect { println(it) }
}
}

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포의 연결 문자열 찾는 방법을 학습 코틀린 (Kotlin) 드라이버 빠른 시작 가이드 의 클러스터에 연결 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

val uri = "mongodb+srv://mongodb-example:27017"

이 예시 제품 주문을 설명하는 문서가 포함된 orders 컬렉션 사용합니다. 각 주문에는 여러 제품이 포함되어 있으므로 집계 의 첫 번째 단계에서는 제품 배열 개별 제품 주문 문서로 압축을 풉니다.

먼저 코틀린 (Kotlin) 데이터 클래스를 만들어 orders 컬렉션 의 데이터를 모델링합니다.

@Serializable
data class Order(
val orderID: Float,
val products: List<Product>
)
@Serializable
data class Product(
val prodID: String,
val name: String,
val price: Int
)

orders 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

val orders = aggDB.getCollection<Order>("orders")
orders.deleteMany(Filters.empty())
orders.insertMany(
listOf(
Order(
6363763262239f, listOf(
Product("abc12345", "Asus Laptop", 431),
Product("def45678", "Karcher Hose Set", 22)
)
),
Order(
1197372932325f, listOf(
Product("abc12345", "Asus Laptop", 429)
)
),
Order(
9812343774839f, listOf(
Product("pqr88223", "Morphy Richards Food Mixer", 431),
Product("def45678", "Karcher Hose Set", 21)
)
),
Order(
4433997244387f, listOf(
Product("def45678", "Karcher Hose Set", 23),
Product("jkl77336", "Picky Pencil Sharpener", 1),
Product("xyz11228", "Russell Hobbs Chrome Kettle", 16)
)
)
)
)

이 집계 튜토리얼을 따라 시작하기 전에 새 Node.js 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

운전자 설치하고 MongoDB 에 연결하는 방법을 학습 Node.js 드라이버 빠른 시작 가이드 참조하세요.

Node.js 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드 참조하세요.

운전자 설치한 후 agg_tutorial.js라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

const { MongoClient } = require("mongodb");
// Replace the placeholder with your connection string.
const uri = "<connection string>";
const client = new MongoClient(uri);
async function run() {
try {
const aggDB = client.db("agg_tutorials_db");
// Get a reference to relevant collections.
// ... const someColl =
// ... const anotherColl =
// Delete any existing documents in collections.
// ... await someColl.deleteMany({});
// Insert sample data into the collection or collections.
// ... const someData = [ ... ];
// ... await someColl.insertMany(someData);
// Create an empty pipeline array.
const pipeline = [];
// Add code to create pipeline stages.
// ... pipeline.push({ ... })
// Run the aggregation.
// ... const aggregationResult = ...
// Print the aggregation results.
for await (const document of aggregationResult) {
console.log(document);
}
} finally {
await client.close();
}
}
run().catch(console.dir);

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포의 연결 문자열 찾는 방법을 학습 Node.js 빠른 시작 가이드 의 연결 문자열 만들기 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

const uri = "mongodb+srv://mongodb-example:27017";

이 예시 제품 주문을 설명하는 문서가 포함된 orders 컬렉션 사용합니다. 각 주문에는 여러 제품이 포함되어 있으므로 집계 의 첫 번째 단계에서는 제품 배열 개별 제품 주문 문서로 압축을 풉니다.

orders 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

const orders = aggDB.collection("orders");
await orders.deleteMany({});
await orders.insertMany([
{
order_id: 6363763262239,
products: [
{
prod_id: "abc12345",
name: "Asus Laptop",
price: 431,
},
{
prod_id: "def45678",
name: "Karcher Hose Set",
price: 22,
},
],
},
{
order_id: 1197372932325,
products: [
{
prod_id: "abc12345",
name: "Asus Laptop",
price: 429,
},
],
},
{
order_id: 9812343774839,
products: [
{
prod_id: "pqr88223",
name: "Morphy Richards Food Mixer",
price: 431,
},
{
prod_id: "def45678",
name: "Karcher Hose Set",
price: 21,
},
],
},
{
order_id: 4433997244387,
products: [
{
prod_id: "def45678",
name: "Karcher Hose Set",
price: 23,
},
{
prod_id: "jkl77336",
name: "Picky Pencil Sharpener",
price: 1,
},
{
prod_id: "xyz11228",
name: "Russell Hobbs Chrome Kettle",
price: 16,
},
],
},
]);

이 집계 튜토리얼을 시작하기 전에 새 PHP 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

PHP 라이브러리를 설치하고 MongoDB 에 연결하는 방법을 학습 PHP 라이브러리 시작하기 튜토리얼을 참조하세요.

PHP 라이브러리에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드 참조하세요.

라이브러리를 설치한 후 agg_tutorial.php라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

<?php
require 'vendor/autoload.php';
// Modify imports for each tutorial as needed.
use MongoDB\Client;
use MongoDB\BSON\UTCDateTime;
use MongoDB\Builder\Pipeline;
use MongoDB\Builder\Stage;
use MongoDB\Builder\Type\Sort;
use MongoDB\Builder\Query;
use MongoDB\Builder\Expression;
use MongoDB\Builder\Accumulator;
use function MongoDB\object;
// Replace the placeholder with your connection string.
$uri = '<connection string>';
$client = new Client($uri);
// Get a reference to relevant collections.
// ... $someColl = $client->agg_tutorials_db->someColl;
// ... $anotherColl = $client->agg_tutorials_db->anotherColl;
// Delete any existing documents in collections if needed.
// ... $someColl->deleteMany([]);
// Insert sample data into the collection or collections.
// ... $someColl->insertMany(...);
// Add code to create pipeline stages within the Pipeline instance.
// ... $pipeline = new Pipeline(...);
// Run the aggregation.
// ... $cursor = $someColl->aggregate($pipeline);
// Print the aggregation results.
foreach ($cursor as $doc) {
echo json_encode($doc, JSON_PRETTY_PRINT), PHP_EOL;
}

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포의 연결 문자열 찾는 방법을 학습 PHP 라이브러리 시작하기 튜토리얼의 연결 문자열 만들기 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

$uri = 'mongodb+srv://mongodb-example:27017';

이 예시 제품 주문을 설명하는 문서가 포함된 orders 컬렉션 사용합니다. 각 주문에는 여러 제품이 포함되어 있으므로 집계 의 첫 번째 단계에서는 제품 배열 개별 제품 주문 문서로 압축을 풉니다.

orders 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

$orders = $client->agg_tutorials_db->orders;
$orders->deleteMany([]);
$orders->insertMany(
[
[
'order_id' => 6363763262239,
'products' => [
[
'prod_id' => 'abc12345',
'name' => 'Asus Laptop',
'price' => 431,
],
[
'prod_id' => 'def45678',
'name' => 'Karcher Hose Set',
'price' => 22,
],
],
],
[
'order_id' => 1197372932325,
'products' => [
[
'prod_id' => 'abc12345',
'name' => 'Asus Laptop',
'price' => 429,
],
],
],
[
'order_id' => 9812343774839,
'products' => [
[
'prod_id' => 'pqr88223',
'name' => 'Morphy Richards Food Mixer',
'price' => 431,
],
[
'prod_id' => 'def45678',
'name' => 'Karcher Hose Set',
'price' => 21,
],
],
],
[
'order_id' => 4433997244387,
'products' => [
[
'prod_id' => 'def45678',
'name' => 'Karcher Hose Set',
'price' => 23,
],
[
'prod_id' => 'jkl77336',
'name' => 'Picky Pencil Sharpener',
'price' => 1,
],
[
'prod_id' => 'xyz11228',
'name' => 'Russell Hobbs Chrome Kettle',
'price' => 16,
],
],
]
]
);

이 집계 튜토리얼을 따라 시작하기 전에 새 Python 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

PyMongo 설치하고 MongoDB 에 연결하는 방법을 학습 PyMongo 시작하기 튜토리얼을 참조하세요.

PyMongo 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드 참조하세요.

라이브러리를 설치한 후 agg_tutorial.py라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

# Modify imports for each tutorial as needed.
from pymongo import MongoClient
# Replace the placeholder with your connection string.
uri = "<connection string>"
client = MongoClient(uri)
try:
agg_db = client["agg_tutorials_db"]
# Get a reference to relevant collections.
# ... some_coll = agg_db["some_coll"]
# ... another_coll = agg_db["another_coll"]
# Delete any existing documents in collections if needed.
# ... some_coll.delete_many({})
# Insert sample data into the collection or collections.
# ... some_coll.insert_many(...)
# Create an empty pipeline array.
pipeline = []
# Add code to create pipeline stages.
# ... pipeline.append({...})
# Run the aggregation.
# ... aggregation_result = ...
# Print the aggregation results.
for document in aggregation_result:
print(document)
finally:
client.close()

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포의 연결 문자열 찾는 방법을 학습 PHP 라이브러리 시작하기 튜토리얼의 연결 문자열 만들기 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

uri = "mongodb+srv://mongodb-example:27017"

이 예시 제품 주문을 설명하는 문서가 포함된 orders 컬렉션 사용합니다. 각 주문에는 여러 제품이 포함되어 있으므로 집계 의 첫 번째 단계에서는 제품 배열 개별 제품 주문 문서로 압축을 풉니다.

orders 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

orders_coll = agg_db["orders"]
orders_coll.delete_many({})
order_data = [
{
"order_id": 6363763262239,
"products": [
{
"prod_id": "abc12345",
"name": "Asus Laptop",
"price": 431,
},
{
"prod_id": "def45678",
"name": "Karcher Hose Set",
"price": 22,
},
],
},
{
"order_id": 1197372932325,
"products": [
{
"prod_id": "abc12345",
"name": "Asus Laptop",
"price": 429,
}
],
},
{
"order_id": 9812343774839,
"products": [
{
"prod_id": "pqr88223",
"name": "Morphy Richards Food Mixer",
"price": 431,
},
{
"prod_id": "def45678",
"name": "Karcher Hose Set",
"price": 21,
},
],
},
{
"order_id": 4433997244387,
"products": [
{
"prod_id": "def45678",
"name": "Karcher Hose Set",
"price": 23,
},
{
"prod_id": "jkl77336",
"name": "Picky Pencil Sharpener",
"price": 1,
},
{
"prod_id": "xyz11228",
"name": "Russell Hobbs Chrome Kettle",
"price": 16,
},
],
},
]
orders_coll.insert_many(order_data)

이 집계 튜토리얼을 따라 시작하기 전에 새 Ruby 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

Ruby 드라이버 설치하고 MongoDB 에 연결하는 방법을 학습 Ruby 드라이버 시작하기 가이드 참조하세요.

Ruby 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드 참조하세요.

운전자 설치한 후 agg_tutorial.rb라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

# typed: strict
require 'mongo'
require 'bson'
# Replace the placeholder with your connection string.
uri = "<connection string>"
Mongo::Client.new(uri) do |client|
agg_db = client.use('agg_tutorials_db')
# Get a reference to relevant collections.
# ... some_coll = agg_db[:some_coll]
# Delete any existing documents in collections if needed.
# ... some_coll.delete_many({})
# Insert sample data into the collection or collections.
# ... some_coll.insert_many( ... )
# Add code to create pipeline stages within the array.
# ... pipeline = [ ... ]
# Run the aggregation.
# ... aggregation_result = some_coll.aggregate(pipeline)
# Print the aggregation results.
aggregation_result.each do |doc|
puts doc
end
end

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포의 연결 문자열 찾는 방법을 학습 Ruby 시작하기 가이드 의 연결 문자열 만들기 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

uri = "mongodb+srv://mongodb-example:27017"

이 예시 제품 주문을 설명하는 문서가 포함된 orders 컬렉션 사용합니다. 각 주문에는 여러 제품이 포함되어 있으므로 집계 의 첫 번째 단계에서는 제품 배열 개별 제품 주문 문서로 압축을 풉니다.

orders 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

orders = agg_db[:orders]
orders.delete_many({})
orders.insert_many(
[
{
order_id: 6363763262239,
products: [
{
prod_id: "abc12345",
name: "Asus Laptop",
price: 431,
},
{
prod_id: "def45678",
name: "Karcher Hose Set",
price: 22,
},
],
},
{
order_id: 1197372932325,
products: [
{
prod_id: "abc12345",
name: "Asus Laptop",
price: 429,
},
],
},
{
order_id: 9812343774839,
products: [
{
prod_id: "pqr88223",
name: "Morphy Richards Food Mixer",
price: 431,
},
{
prod_id: "def45678",
name: "Karcher Hose Set",
price: 21,
},
],
},
{
order_id: 4433997244387,
products: [
{
prod_id: "def45678",
name: "Karcher Hose Set",
price: 23,
},
{
prod_id: "jkl77336",
name: "Picky Pencil Sharpener",
price: 1,
},
{
prod_id: "xyz11228",
name: "Russell Hobbs Chrome Kettle",
price: 16,
},
],
},
]
)

이 집계 튜토리얼을 시작하기 전에 새 Rust 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

운전자 설치하고 MongoDB 에 연결하는 방법을 학습 Rust 드라이버 빠른 시작 가이드 참조하세요.

Rust 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드 참조하세요.

운전자 설치한 후 agg-tutorial.rs라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

use mongodb::{
bson::{doc, Document},
options::ClientOptions,
Client,
};
use futures::stream::TryStreamExt;
use std::error::Error;
// Define structs.
// #[derive(Debug, Serialize, Deserialize)]
// struct MyStruct { ... }
#[tokio::main]
async fn main() mongodb::error::Result<()> {
// Replace the placeholder with your connection string.
let uri = "<connection string>";
let client = Client::with_uri_str(uri).await?;
let agg_db = client.database("agg_tutorials_db");
// Get a reference to relevant collections.
// ... let some_coll: Collection<T> = agg_db.collection("...");
// ... let another_coll: Collection<T> = agg_db.collection("...");
// Delete any existing documents in collections if needed.
// ... some_coll.delete_many(doc! {}).await?;
// Insert sample data into the collection or collections.
// ... some_coll.insert_many(vec![...]).await?;
// Create an empty pipeline.
let mut pipeline = Vec::new();
// Add code to create pipeline stages.
// pipeline.push(doc! { ... });
// Run the aggregation and print the results.
let mut results = some_coll.aggregate(pipeline).await?;
while let Some(result) = results.try_next().await? {
println!("{:?}\n", result);
}
Ok(())
}

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포서버의 연결 문자열 찾는 방법을 학습 Rust 빠른 시작 가이드 의 연결 문자열 만들기 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

let uri = "mongodb+srv://mongodb-example:27017";

이 예시 제품 주문을 설명하는 문서가 포함된 orders 컬렉션 사용합니다. 각 주문에는 여러 제품이 포함되어 있으므로 집계 의 첫 번째 단계에서는 제품 배열 개별 제품 주문 문서로 압축을 풉니다.

먼저 Rust 구조체를 만들어 orders 컬렉션 의 데이터를 모델링합니다.

#[derive(Debug, Serialize, Deserialize)]
struct Product {
prod_id: String,
name: String,
price: i32,
}
#[derive(Debug, Serialize, Deserialize)]
struct Order {
order_id: i64,
products: Vec<Product>,
}

orders 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

let orders_coll: Collection<Order> = agg_db.collection("orders");
orders.delete_many(doc! {}).await?;
let orders = vec![
Order {
order_id: 6363763262239,
products: vec![
Product {
prod_id: "abc12345".to_string(),
name: "Asus Laptop".to_string(),
price: 431,
},
Product {
prod_id: "def45678".to_string(),
name: "Karcher Hose Set".to_string(),
price: 22,
},
],
},
Order {
order_id: 1197372932325,
products: vec![Product {
prod_id: "abc12345".to_string(),
name: "Asus Laptop".to_string(),
price: 429,
}],
},
Order {
order_id: 9812343774839,
products: vec![
Product {
prod_id: "pqr88223".to_string(),
name: "Morphy Richards Food Mixer".to_string(),
price: 431,
},
Product {
prod_id: "def45678".to_string(),
name: "Karcher Hose Set".to_string(),
price: 21,
},
],
},
Order {
order_id: 4433997244387,
products: vec![
Product {
prod_id: "def45678".to_string(),
name: "Karcher Hose Set".to_string(),
price: 23,
},
Product {
prod_id: "jkl77336".to_string(),
name: "Picky Pencil Sharpene".to_string(),
price: 1,
},
Product {
prod_id: "xyz11228".to_string(),
name: "Russell Hobbs Chrome Kettle".to_string(),
price: 16,
},
],
},
];
orders_coll.insert_many(orders).await?;

집계 튜토리얼을 시작하기 전에 새 스칼라 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

운전자 설치하고 MongoDB 에 연결하는 방법을 학습 스칼라 드라이버 시작하기 가이드 참조하세요.

스칼라 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드 참조하세요.

운전자 설치한 후 AggTutorial.scala라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

package org.example;
// Modify imports for each tutorial as needed.
import org.mongodb.scala.MongoClient
import org.mongodb.scala.bson.Document
import org.mongodb.scala.model.{Accumulators, Aggregates, Field, Filters, Variable}
import java.text.SimpleDateFormat
object FilteredSubset {
def main(args: Array[String]): Unit = {
// Replace the placeholder with your connection string.
val uri = "<connection string>"
val mongoClient = MongoClient(uri)
Thread.sleep(1000)
val aggDB = mongoClient.getDatabase("agg_tutorials_db")
// Get a reference to relevant collections.
// ... val someColl = aggDB.getCollection("someColl")
// ... val anotherColl = aggDB.getCollection("anotherColl")
// Delete any existing documents in collections if needed.
// ... someColl.deleteMany(Filters.empty()).subscribe(...)
// If needed, create the date format template.
val dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
// Insert sample data into the collection or collections.
// ... someColl.insertMany(...).subscribe(...)
Thread.sleep(1000)
// Add code to create pipeline stages within the Seq.
// ... val pipeline = Seq(...)
// Run the aggregation and print the results.
// ... someColl.aggregate(pipeline).subscribe(...)
Thread.sleep(1000)
mongoClient.close()
}
}

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포의 연결 문자열 찾는 방법을 학습 스칼라 드라이버 시작하기 가이드 의 연결 문자열 만들기 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

val uri = "mongodb+srv://mongodb-example:27017"

이 예시 제품 주문을 설명하는 문서가 포함된 orders 컬렉션 사용합니다. 각 주문에는 여러 제품이 포함되어 있으므로 집계 의 첫 번째 단계에서는 제품 배열 개별 제품 주문 문서로 압축을 풉니다.

orders 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

val orders = aggDB.getCollection("orders")
orders.deleteMany(Filters.empty()).subscribe(
_ => {},
e => println("Error: " + e.getMessage),
)
orders.insertMany(Seq(
Document(
"order_id" -> 6363763262239L,
"products" -> Seq(
Document(
"prod_id" -> "abc12345",
"name" -> "Asus Laptop",
"price" -> 431
),
Document(
"prod_id" -> "def45678",
"name" -> "Karcher Hose Set",
"price" -> 22
)
)
),
Document(
"order_id" -> 1197372932325L,
"products" -> Seq(
Document(
"prod_id" -> "abc12345",
"name" -> "Asus Laptop",
"price" -> 429
)
)
),
Document(
"order_id" -> 9812343774839L,
"products" -> Seq(
Document(
"prod_id" -> "pqr88223",
"name" -> "Morphy Richards Food Mixer",
"price" -> 431
),
Document(
"prod_id" -> "def45678",
"name" -> "Karcher Hose Set",
"price" -> 21
)
)
),
Document(
"order_id" -> 4433997244387L,
"products" -> Seq(
Document(
"prod_id" -> "def45678",
"name" -> "Karcher Hose Set",
"price" -> 23
),
Document(
"prod_id" -> "jkl77336",
"name" -> "Picky Pencil Sharpener",
"price" -> 1
),
Document(
"prod_id" -> "xyz11228",
"name" -> "Russell Hobbs Chrome Kettle",
"price" -> 16
)
)
)
)).subscribe(
_ => {},
e => println("Error: " + e.getMessage),
)

다음 단계에서는 집계 파이프라인 만들고 실행 배열 필드를 별도의 문서로 압축을 풀고 공통 값 그룹을 기반으로 새 값을 계산하는 방법을 보여 줍니다.

1
db.orders.aggregate( [
// Stage 1: Unwind the array of product orders
{ $unwind: { path: "$products" } },
// Stage 2: Match products that cost more than $15
{ $match: { "products.price": { $gt: 15 } } },
// Stage 3: Group products by product type
{ $group:
{
_id: "$products.prod_id",
product: { $first: "$products.name" },
total_value: { $sum: "$products.price" },
quantity: { $sum: 1 }
}
},
// Stage 4: Display the product ID
{ $set: { product_id: "$_id" } },
// Stage 5: Remove unneeded fields
{ $unset: [ "_id"] }
] )
2

이 애그리게이션은 2020년의 고객 주문에 대한 다음과 같은 요약을 반환합니다.

{
product: 'Asus Laptop',
total_value: 860,
quantity: 2,
product_id: 'abc12345'
}
{
product: 'Morphy Richards Food Mixer',
total_value: 431,
quantity: 1,
product_id: 'pqr88223'
}
{
product: 'Russell Hobbs Chrome Kettle',
total_value: 16,
quantity: 1,
product_id: 'xyz11228'
}
{
product: 'Karcher Hose Set',
total_value: 66,
quantity: 3,
product_id: 'def45678'
}

참고

이 예시 실행 집계 파이프라인 에 정렬 단계가 없기 때문에 결과의 문서 순서가 이 페이지의 문서 순서와 다를 수 있습니다.

1

먼저 단계를 추가하여 배열 의 $unwind 항목을 products 개별 문서로 분리합니다.

"{", "$unwind", "{", "path", BCON_UTF8("$products"), "}", "}",
2

다음으로, 값이 보다 큰 제품과 $match 일치하는 단계를 products.price 15 추가합니다.

"{", "$match", "{", "products.price", "{", "$gt", BCON_INT32(15), "}", "}", "}",
3

단계를 추가하여 필드 $group 값으로 주문 문서를 수집합니다. 이 단계에서는 결과 문서에 다음 필드를 생성하는 집계 작업을 추가합니다.prod_id

  • product: 제품 이름

  • total_value: 제품의 모든 판매의 총 가치

  • quantity: 제품의 주문 수

"{", "$group", "{",
"_id", BCON_UTF8("$products.prod_id"),
"product", "{", "$first", BCON_UTF8("$products.name"), "}",
"total_value", "{", "$sum", BCON_UTF8("$products.price"), "}",
"quantity", "{", "$sum", BCON_INT32(1), "}",
"}", "}",
4

단계를 $set 추가하여 단계에서 설정하다 필드 의 값으로 product_id _id 필드 다시 $group 만듭니다.

"{", "$set", "{", "product_id", BCON_UTF8("$_id"), "}", "}",
5

마지막으로 단계를 $unset 추가합니다.$unset 단계는 _id 결과 문서에서 필드 제거합니다.

"{", "$unset", "[", BCON_UTF8("_id"), "]", "}",
6

orders collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

mongoc_cursor_t *results =
mongoc_collection_aggregate(orders, MONGOC_QUERY_NONE, pipeline, NULL, NULL);
bson_destroy(pipeline);

정리 문에 다음 줄을 추가하여 컬렉션 리소스를 정리해야 합니다.

mongoc_collection_destroy(orders);

마지막으로 셸 에서 다음 명령을 실행 실행 파일을 생성하고 실행 .

gcc -o aggc agg-tutorial.c $(pkg-config --libs --cflags libmongoc-1.0)
./aggc

한 번의 호출에서 앞의 명령을 실행 데 연결 오류가 발생하는 경우 별도로 실행 수 있습니다.

7

이 애그리게이션은 2020년의 고객 주문에 대한 다음과 같은 요약을 반환합니다.

{ "product" : "Asus Laptop", "total_value" : { "$numberInt" : "860" }, "quantity" : { "$numberInt" : "2" }, "product_id" : "abc12345" }
{ "product" : "Karcher Hose Set", "total_value" : { "$numberInt" : "66" }, "quantity" : { "$numberInt" : "3" }, "product_id" : "def45678" }
{ "product" : "Morphy Richards Food Mixer", "total_value" : { "$numberInt" : "431" }, "quantity" : { "$numberInt" : "1" }, "product_id" : "pqr88223" }
{ "product" : "Russell Hobbs Chrome Kettle", "total_value" : { "$numberInt" : "16" }, "quantity" : { "$numberInt" : "1" }, "product_id" : "xyz11228" }

결과 문서에는 비용이 $15 이상인 제품의 총 주문 금액과 수량에 대한 세부 정보가 포함되어 있습니다.

1

먼저 단계를 추가하여 배열 의 $unwind 항목을 products 개별 문서로 분리합니다.

pipeline.unwind("$products");
2

다음으로, 값이 보다 큰 제품과 $match 일치하는 단계를 products.price 15 추가합니다.

pipeline.match(bsoncxx::from_json(R"({
"products.price": { "$gt": 15 }
})"));
3

단계를 추가하여 필드 $group 값으로 주문 문서를 수집합니다. 이 단계에서는 결과 문서에 다음 필드를 생성하는 집계 작업을 추가합니다.prod_id

  • product: 제품 이름

  • total_value: 제품의 모든 판매의 총 가치

  • quantity: 제품의 주문 수

pipeline.group(bsoncxx::from_json(R"({
"_id": "$products.prod_id",
"product": { "$first": "$products.name" },
"total_value": { "$sum": "$products.price" },
"quantity": { "$sum": 1 }
})"));
4

단계를 추가하여 단계에서 설정하다 한 $addFields product_id 필드 의 값에서 _id 필드 다시 $group 만듭니다.

pipeline.add_fields(bsoncxx::from_json(R"({
"product_id": "$_id"
})"));
5

마지막으로 단계를 $unset 추가합니다.$unset 단계는 _id 결과 문서에서 필드 제거합니다.

pipeline.append_stage(bsoncxx::from_json(R"({
"$unset": ["_id"]
})"));
6

orders collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

auto cursor = orders.aggregate(pipeline);

마지막으로 shell에서 다음 명령을 실행하여 애플리케이션을 시작합니다.

c++ --std=c++17 agg-tutorial.cpp $(pkg-config --cflags --libs libmongocxx) -o ./app.out
./app.out
7

이 애그리게이션은 2020년의 고객 주문에 대한 다음과 같은 요약을 반환합니다.

{ "product" : "Karcher Hose Set", "total_value" : 66, "quantity" : 3, "product_id" : "def45678" }
{ "product" : "Asus Laptop", "total_value" : 860, "quantity" : 2, "product_id" : "abc12345" }
{ "product" : "Morphy Richards Food Mixer", "total_value" : 431, "quantity" : 1, "product_id" : "pqr88223" }
{ "product" : "Russell Hobbs Chrome Kettle", "total_value" : 16, "quantity" : 1, "product_id" : "xyz11228" }

결과 문서에는 비용이 $15 이상인 제품의 총 주문 금액과 수량에 대한 세부 정보가 포함되어 있습니다.

1

먼저 컬렉션 에서 집계 을 orders 시작하고 단계를 체인으로 $unwind 연결하여 배열 의 항목을 Products 개별 문서로 분리합니다.

var results = orders.Aggregate()
.Unwind<Order, OrderUnwound>(o => o.Products)
2

다음으로, 값이 보다 큰 제품과 $match 일치하는 단계를 Products.Price 15 추가합니다.

.Match(o => o.Products.Price > 15)
3

단계를 추가하여 필드 $group 값으로 주문 문서를 수집합니다. 이 단계에서는 결과 문서에 다음 필드를 생성하는 집계 작업을 추가합니다.ProductId

  • ProductId: 제품 ID (그룹화 키)

  • Product: 제품 이름

  • TotalValue: 제품의 모든 판매의 총 가치

  • Quantity: 제품의 주문 수

.Group(
id: o => o.Products.ProductId,
group: g => new
{
ProductId = g.Key,
Product = g.First().Products.Name,
TotalValue = g.Sum(o => o.Products.Price),
Quantity = g.Count(),
}
);
4

마지막으로 IDE에서 애플리케이션 실행 하고 결과를 검사합니다.

이 애그리게이션은 2020년의 고객 주문에 대한 다음과 같은 요약을 반환합니다.

{ ProductId = pqr88223, Product = Morphy Richards Food Mixer, TotalValue = 431, Quantity = 1 }
{ ProductId = xyz11228, Product = Russell Hobbs Chrome Kettle, TotalValue = 16, Quantity = 1 }
{ ProductId = abc12345, Product = Asus Laptop, TotalValue = 860, Quantity = 2 }
{ ProductId = def45678, Product = Karcher Hose Set, TotalValue = 66, Quantity = 3 }

결과 문서에는 비용이 $15 이상인 제품의 총 주문 금액과 수량에 대한 세부 정보가 포함되어 있습니다.

1

먼저 단계를 추가하여 배열 의 $unwind 항목을 products 개별 문서로 분리합니다.

unwindStage := bson.D{{Key: "$unwind", Value: bson.D{
{Key: "path", Value: "$products"},
}}}
2

다음으로, 값이 보다 큰 제품과 $match 일치하는 단계를 products.price 15 추가합니다.

matchStage := bson.D{{Key: "$match", Value: bson.D{
{Key: "products.price", Value: bson.D{{Key: "$gt", Value: 15}}},
}}}
3

단계를 추가하여 필드 $group 값으로 주문 문서를 수집합니다. 이 단계에서는 결과 문서에 다음 필드를 생성하는 집계 작업을 추가합니다.prod_id

  • product: 제품 이름

  • total_value: 제품의 모든 판매의 총 가치

  • quantity: 제품의 주문 수

groupStage := bson.D{{Key: "$group", Value: bson.D{
{Key: "_id", Value: "$products.prod_id"},
{Key: "product", Value: bson.D{{Key: "$first", Value: "$products.name"}}},
{Key: "total_value", Value: bson.D{{Key: "$sum", Value: "$products.price"}}},
{Key: "quantity", Value: bson.D{{Key: "$sum", Value: 1}}},
}}}
4

단계를 $set 추가하여 단계에서 설정하다 필드 의 값으로 product_id _id 필드 다시 $group 만듭니다.

setStage := bson.D{{Key: "$set", Value: bson.D{
{Key: "product_id", Value: "$_id"},
}}}
5

마지막으로 단계를 $unset 추가합니다.$unset 단계는 _id 결과 문서에서 필드 제거합니다.

unsetStage := bson.D{{Key: "$unset", Value: bson.A{"_id"}}}
6

orders collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

pipeline := mongo.Pipeline{unwindStage, matchStage, groupStage, setStage, unsetStage}
cursor, err := orders.Aggregate(context.TODO(), pipeline)

마지막으로 shell에서 다음 명령을 실행하여 애플리케이션을 시작합니다.

go run agg_tutorial.go
7

이 애그리게이션은 2020년의 고객 주문에 대한 다음과 같은 요약을 반환합니다.

{"product":"Morphy Richards Food Mixer","total_value":431,"quantity":1,"product_id":"pqr88223"}
{"product":"Russell Hobbs Chrome Kettle","total_value":16,"quantity":1,"product_id":"xyz11228"}
{"product":"Karcher Hose Set","total_value":66,"quantity":3,"product_id":"def45678"}
{"product":"Asus Laptop","total_value":860,"quantity":2,"product_id":"abc12345"}

결과 문서에는 비용이 $15 이상인 제품의 총 주문 금액과 수량에 대한 세부 정보가 포함되어 있습니다.

1

먼저 단계를 추가하여 배열 의 $unwind 항목을 products 개별 문서로 분리합니다.

pipeline.add(Aggregates.unwind("$products"));
2

다음으로, 값이 보다 큰 제품과 $match 일치하는 단계를 products.price 15 추가합니다.

pipeline.add(Aggregates.match(
Filters.gt("products.price", 15)
));
3

단계를 추가하여 필드 $group 값으로 주문 문서를 수집합니다. 이 단계에서는 결과 문서에 다음 필드를 생성하는 집계 작업을 추가합니다.prod_id

  • product: 제품 이름

  • total_value: 제품의 모든 판매의 총 가치

  • quantity: 제품의 주문 수

pipeline.add(Aggregates.group(
"$products.prod_id",
Accumulators.first("product", "$products.name"),
Accumulators.sum("total_value", "$products.price"),
Accumulators.sum("quantity", 1)
));
4

단계를 $set 추가하여 단계에서 설정하다 필드 의 값으로 product_id _id 필드 다시 $group 만듭니다.

pipeline.add(Aggregates.set(new Field<>("product_id", "$_id")));
5

마지막으로 단계를 $unset 추가합니다.$unset 단계는 _id 결과 문서에서 필드 제거합니다.

pipeline.add(Aggregates.unset("_id"));
6

orders collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

AggregateIterable<Document> aggregationResult = orders.aggregate(pipeline);

마지막으로 IDE에서 애플리케이션 실행 .

7

이 애그리게이션은 2020년의 고객 주문에 대한 다음과 같은 요약을 반환합니다.

{"product": "Asus Laptop", "total_value": 860, "quantity": 2, "product_id": "abc12345"}
{"product": "Russell Hobbs Chrome Kettle", "total_value": 16, "quantity": 1, "product_id": "xyz11228"}
{"product": "Karcher Hose Set", "total_value": 66, "quantity": 3, "product_id": "def45678"}
{"product": "Morphy Richards Food Mixer", "total_value": 431, "quantity": 1, "product_id": "pqr88223"}

결과 문서에는 비용이 $15 이상인 제품의 총 주문 금액과 수량에 대한 세부 정보가 포함되어 있습니다.

1

먼저 단계를 추가하여 배열 의 $unwind 항목을 products 개별 문서로 분리합니다.

pipeline.add(
Aggregates.unwind("\$${Order::products.name}")
)
2

다음으로, 값이 보다 큰 제품과 $match 일치하는 단계를 products.price 15 추가합니다.

pipeline.add(
Aggregates.match(
Filters.gt("${Order::products.name}.${Product::price.name}", 15)
)
)
3

단계를 추가하여 필드 $group 값으로 주문 문서를 수집합니다. 이 단계에서는 결과 문서에 다음 필드를 생성하는 집계 작업을 추가합니다.prodID

  • product: 제품 이름

  • total_value: 제품의 모든 판매의 총 가치

  • quantity: 제품의 주문 수

pipeline.add(
Aggregates.group(
"\$${Order::products.name}.${Product::prodID.name}",
Accumulators.first("product", "\$${Order::products.name}.${Product::name.name}"),
Accumulators.sum("total_value", "\$${Order::products.name}.${Product::price.name}"),
Accumulators.sum("quantity", 1)
)
)
4

단계를 $set 추가하여 단계에서 설정하다 필드 의 값으로 product_id _id 필드 다시 $group 만듭니다.

pipeline.add(Aggregates.set(Field("product_id", "\$_id")))
5

마지막으로 단계를 $unset 추가합니다.$unset 단계는 _id 결과 문서에서 필드 제거합니다.

pipeline.add(Aggregates.unset("_id"))
6

orders collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

val aggregationResult = orders.aggregate<Document>(pipeline)

마지막으로 IDE에서 애플리케이션 실행 .

7

이 애그리게이션은 2020년의 고객 주문에 대한 다음과 같은 요약을 반환합니다.

Document{{product=Russell Hobbs Chrome Kettle, total_value=16, quantity=1, product_id=xyz11228}}
Document{{product=Karcher Hose Set, total_value=66, quantity=3, product_id=def45678}}
Document{{product=Morphy Richards Food Mixer, total_value=431, quantity=1, product_id=pqr88223}}
Document{{product=Asus Laptop, total_value=860, quantity=2, product_id=abc12345}}

결과 문서에는 비용이 $15 이상인 제품의 총 주문 금액과 수량에 대한 세부 정보가 포함되어 있습니다.

1

먼저 단계를 추가하여 배열 의 $unwind 항목을 products 개별 문서로 분리합니다.

pipeline.push({
$unwind: {
path: "$products",
},
});
2

다음으로, 값이 보다 큰 제품과 $match 일치하는 단계를 products.price 15 추가합니다.

pipeline.push({
$match: {
"products.price": {
$gt: 15,
},
},
});
3

단계를 추가하여 필드 $group 값으로 주문 문서를 수집합니다. 이 단계에서는 결과 문서에 다음 필드를 생성하는 집계 작업을 추가합니다.prod_id

  • product: 제품 이름

  • total_value: 제품의 모든 판매의 총 가치

  • quantity: 제품의 주문 수

pipeline.push({
$group: {
_id: "$products.prod_id",
product: { $first: "$products.name" },
total_value: { $sum: "$products.price" },
quantity: { $sum: 1 },
},
});
4

단계를 $set 추가하여 단계에서 설정하다 필드 의 값으로 product_id _id 필드 다시 $group 만듭니다.

pipeline.push({
$set: {
product_id: "$_id",
},
});
5

마지막으로 단계를 $unset 추가합니다.$unset 단계는 _id 결과 문서에서 필드 제거합니다.

pipeline.push({ $unset: ["_id"] });
6

orders collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

const aggregationResult = await orders.aggregate(pipeline);

마지막으로 shell에서 다음 명령을 실행하여 애플리케이션을 시작합니다.

node agg_tutorial.js
7

이 애그리게이션은 2020년의 고객 주문에 대한 다음과 같은 요약을 반환합니다.

{
product: 'Asus Laptop',
total_value: 860,
quantity: 2,
product_id: 'abc12345'
}
{
product: 'Morphy Richards Food Mixer',
total_value: 431,
quantity: 1,
product_id: 'pqr88223'
}
{
product: 'Russell Hobbs Chrome Kettle',
total_value: 16,
quantity: 1,
product_id: 'xyz11228'
}
{
product: 'Karcher Hose Set',
total_value: 66,
quantity: 3,
product_id: 'def45678'
}

결과 문서에는 비용이 $15 이상인 제품의 총 주문 금액과 수량에 대한 세부 정보가 포함되어 있습니다.

1

먼저 단계를 추가하여 배열 의 $unwind 항목을 products 개별 문서로 분리합니다.

Stage::unwind(
path: Expression::arrayFieldPath('products')
),
2

다음으로, 값이 보다 큰 제품과 $match 일치하는 단계를 products.price 15 추가합니다.

Stage::match(
['products.price' => Query::gt(15)]
),
3

인스턴스 외부 Pipeline 에 필드 값으로 주문 문서 를 수집 $group 하는 팩토리 함수 에 단계 를 만듭니다 prod_id . 이 단계에서는 결과 문서에 다음 필드를 생성하는 집계 작업을 추가합니다.

  • product: 제품 이름

  • total_value: 제품의 모든 판매의 총 가치

  • quantity: 제품의 주문 수

function groupByProductStage()
{
return Stage::group(
_id: Expression::stringFieldPath('products.prod_id'),
product: Accumulator::first(
Expression::stringFieldPath('products.name')
),
total_value: Accumulator::sum(
Expression::numberFieldPath('products.price'),
),
quantity: Accumulator::sum(1)
);
}

그런 다음 Pipeline 인스턴스 에서 groupByProductStage() 함수를 호출합니다.

groupByProductStage(),
4

단계를 $set 추가하여 단계에서 설정하다 필드 의 값으로 product_id _id 필드 다시 $group 만듭니다.

Stage::set(product_id: Expression::stringFieldPath('_id')),
5

마지막으로 단계를 $unset 추가합니다.$unset 단계는 _id 결과 문서에서 필드 제거합니다.

Stage::unset('_id')
6

orders collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

$cursor = $orders->aggregate($pipeline);

마지막으로 shell에서 다음 명령을 실행하여 애플리케이션을 시작합니다.

php agg_tutorial.php
7

이 애그리게이션은 2020년의 고객 주문에 대한 다음과 같은 요약을 반환합니다.

{
"product": "Russell Hobbs Chrome Kettle",
"total_value": 16,
"quantity": 1,
"product_id": "xyz11228"
}
{
"product": "Asus Laptop",
"total_value": 860,
"quantity": 2,
"product_id": "abc12345"
}
{
"product": "Karcher Hose Set",
"total_value": 66,
"quantity": 3,
"product_id": "def45678"
}
{
"product": "Morphy Richards Food Mixer",
"total_value": 431,
"quantity": 1,
"product_id": "pqr88223"
}

결과 문서에는 비용이 $15 이상인 제품의 총 주문 금액과 수량에 대한 세부 정보가 포함되어 있습니다.

1

먼저 단계를 추가하여 배열 의 $unwind 항목을 products 개별 문서로 분리합니다.

pipeline.append({"$unwind": {"path": "$products"}})
2

다음으로, 값이 보다 큰 제품과 $match 일치하는 단계를 products.price 15 추가합니다.

pipeline.append({"$match": {"products.price": {"$gt": 15}}})
3

단계를 추가하여 필드 $group 값으로 주문 문서를 수집합니다. 이 단계에서는 결과 문서에 다음 필드를 생성하는 집계 작업을 추가합니다.prod_id

  • product: 제품 이름

  • total_value: 제품의 모든 판매의 총 가치

  • quantity: 제품의 주문 수

pipeline.append(
{
"$group": {
"_id": "$products.prod_id",
"product": {"$first": "$products.name"},
"total_value": {"$sum": "$products.price"},
"quantity": {"$sum": 1},
}
}
)
4

단계를 $set 추가하여 단계에서 설정하다 필드 의 값으로 product_id _id 필드 다시 $group 만듭니다.

pipeline.append({"$set": {"product_id": "$_id"}})
5

마지막으로 단계를 $unset 추가합니다.$unset 단계는 _id 결과 문서에서 필드 제거합니다.

pipeline.append({"$unset": ["_id"]})
6

orders collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

aggregation_result = orders_coll.aggregate(pipeline)

마지막으로 shell에서 다음 명령을 실행하여 애플리케이션을 시작합니다.

python3 agg_tutorial.py
7

이 애그리게이션은 2020년의 고객 주문에 대한 다음과 같은 요약을 반환합니다.

{'product': 'Morphy Richards Food Mixer', 'total_value': 431, 'quantity': 1, 'product_id': 'pqr88223'}
{'product': 'Asus Laptop', 'total_value': 860, 'quantity': 2, 'product_id': 'abc12345'}
{'product': 'Russell Hobbs Chrome Kettle', 'total_value': 16, 'quantity': 1, 'product_id': 'xyz11228'}
{'product': 'Karcher Hose Set', 'total_value': 66, 'quantity': 3, 'product_id': 'def45678'}

결과 문서에는 비용이 $15 이상인 제품의 총 주문 금액과 수량에 대한 세부 정보가 포함되어 있습니다.

1

먼저 단계를 추가하여 배열 의 $unwind 항목을 products 개별 문서로 분리합니다.

{
"$unwind": {
path: "$products",
},
},
2

다음으로, 값이 보다 큰 제품과 $match 일치하는 단계를 products.price 15 추가합니다.

{
"$match": {
"products.price": {
"$gt": 15,
},
},
},
3

단계를 추가하여 필드 $group 값으로 주문 문서를 수집합니다. 이 단계에서는 결과 문서에 다음 필드를 생성하는 집계 작업을 추가합니다.prod_id

  • product: 제품 이름

  • total_value: 제품의 모든 판매의 총 가치

  • quantity: 제품의 주문 수

{
"$group": {
_id: "$products.prod_id",
product: { "$first": "$products.name" },
total_value: { "$sum": "$products.price" },
quantity: { "$sum": 1 },
},
},
4

단계를 $set 추가하여 단계에서 설정하다 필드 의 값으로 product_id _id 필드 다시 $group 만듭니다.

{
"$set": {
product_id: "$_id",
},
},
5

마지막으로 단계를 $unset 추가합니다.$unset 단계는 _id 결과 문서에서 필드 제거합니다.

{ "$unset": ["_id"] },
6

orders collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

aggregation_result = orders.aggregate(pipeline)

마지막으로 shell에서 다음 명령을 실행하여 애플리케이션을 시작합니다.

ruby agg_tutorial.rb
7

이 애그리게이션은 2020년의 고객 주문에 대한 다음과 같은 요약을 반환합니다.

{"product"=>"Asus Laptop", "total_value"=>860, "quantity"=>2, "product_id"=>"abc12345"}
{"product"=>"Russell Hobbs Chrome Kettle", "total_value"=>16, "quantity"=>1, "product_id"=>"xyz11228"}
{"product"=>"Karcher Hose Set", "total_value"=>66, "quantity"=>3, "product_id"=>"def45678"}
{"product"=>"Morphy Richards Food Mixer", "total_value"=>431, "quantity"=>1, "product_id"=>"pqr88223"}

결과 문서에는 비용이 $15 이상인 제품의 총 주문 금액과 수량에 대한 세부 정보가 포함되어 있습니다.

1

먼저 단계를 추가하여 배열 의 $unwind 항목을 products 개별 문서로 분리합니다.

pipeline.push(doc! {
"$unwind": {
"path": "$products"
}
});
2

다음으로, 값이 보다 큰 제품과 $match 일치하는 단계를 products.price 15 추가합니다.

pipeline.push(doc! {
"$match": {
"products.price": { "$gt": 15 }
}
});
3

단계를 추가하여 필드 $group 값으로 주문 문서를 수집합니다. 이 단계에서는 결과 문서에 다음 필드를 생성하는 집계 작업을 추가합니다.prod_id

  • product: 제품 이름

  • total_value: 제품의 모든 판매의 총 가치

  • quantity: 제품의 주문 수

pipeline.push(doc! {
"$group": {
"_id": "$products.prod_id",
"product": { "$first": "$products.name" },
"total_value": { "$sum": "$products.price" },
"quantity": { "$sum": 1 }
}
});
4

단계를 $set 추가하여 단계에서 설정하다 필드 의 값으로 prod_id _id 필드 다시 $group 만듭니다.

pipeline.push(doc! {
"$set": {
"prod_id": "$_id"
}
});
5

마지막으로 단계를 $unset 추가합니다.$unset 단계는 _id 결과 문서에서 필드 제거합니다.

pipeline.push(doc! {
"$unset": ["_id"]
});
6

orders collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

let mut cursor = orders_coll.aggregate(pipeline).await?;

마지막으로 shell에서 다음 명령을 실행하여 애플리케이션을 시작합니다.

cargo run
7

이 애그리게이션은 2020년의 고객 주문에 대한 다음과 같은 요약을 반환합니다.

Document({"product": String("Russell Hobbs Chrome Kettle"), "total_value": Int32(16), "quantity": Int32(1),
"prod_id": String("xyz11228")})
Document({"product": String("Morphy Richards Food Mixer"), "total_value": Int32(431), "quantity": Int32(1),
"prod_id": String("pqr88223")})
Document({"product": String("Karcher Hose Set"), "total_value": Int32(66), "quantity": Int32(3),
"prod_id": String("def45678")})
Document({"product": String("Asus Laptop"), "total_value": Int32(860), "quantity": Int32(2),
"prod_id": String("abc12345")})

결과 문서에는 비용이 $15 이상인 제품의 총 주문 금액과 수량에 대한 세부 정보가 포함되어 있습니다.

1

먼저 단계를 추가하여 배열 의 $unwind 항목을 products 개별 문서로 분리합니다.

Aggregates.unwind("$products"),
2

다음으로, 값이 보다 큰 제품과 $match 일치하는 단계를 products.price 15 추가합니다.

Aggregates.filter(Filters.gt("products.price", 15)),
3

단계를 추가하여 필드 $group 값으로 주문 문서를 수집합니다. 이 단계에서는 결과 문서에 다음 필드를 생성하는 집계 작업을 추가합니다.prod_id

  • product: 제품 이름

  • total_value: 제품의 모든 판매의 총 가치

  • quantity: 제품의 주문 수

Aggregates.group(
"$products.prod_id",
Accumulators.first("product", "$products.name"),
Accumulators.sum("total_value", "$products.price"),
Accumulators.sum("quantity", 1)
),
4

단계를 $set 추가하여 단계에서 설정하다 필드 의 값으로 product_id _id 필드 다시 $group 만듭니다.

Aggregates.set(Field("product_id", "$_id")),
5

마지막으로 단계를 $unset 추가합니다.$unset 단계는 _id 결과 문서에서 필드 제거합니다.

Aggregates.unset("_id")
6

orders collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

orders.aggregate(pipeline)
.subscribe((doc: Document) => println(doc.toJson()),
(e: Throwable) => println(s"Error: $e"))

마지막으로 IDE에서 애플리케이션 실행 .

7

이 애그리게이션은 2020년의 고객 주문에 대한 다음과 같은 요약을 반환합니다.

{"product": "Morphy Richards Food Mixer", "total_value": 431, "quantity": 1, "product_id": "pqr88223"}
{"product": "Karcher Hose Set", "total_value": 66, "quantity": 3, "product_id": "def45678"}
{"product": "Russell Hobbs Chrome Kettle", "total_value": 16, "quantity": 1, "product_id": "xyz11228"}
{"product": "Asus Laptop", "total_value": 860, "quantity": 2, "product_id": "abc12345"}

결과 문서에는 비용이 $15 이상인 제품의 총 주문 금액과 수량에 대한 세부 정보가 포함되어 있습니다.

돌아가기

그룹 및 합계

이 페이지의 내용