이 튜토리얼에서는 집계 파이프라인 구성하고, 컬렉션 에서 집계 수행하고, 선택한 언어 사용하여 결과를 표시하는 방법을 보여 줍니다.
이 작업에 관한 정보
이 튜토리얼에서는 제품 정보를 설명하는 컬렉션 의 데이터를 고객 주문을 설명하는 다른 컬렉션 과 결합하는 방법을 보여 줍니다. 결과에는 2020 에서 주문한 제품 목록과 각 주문에 대한 세부 정보가 표시됩니다.
이 집계 를 사용하여 다중 필드 조인을 $lookup
수행합니다. 다중 필드 조인은 두 컬렉션의 문서에 해당 필드가 여러 개 있는 경우 발생합니다. 집계 해당 필드에서 이러한 문서를 일치시키고 두 문서의 정보를 하나의 문서 로 결합합니다.
시작하기 전에
오른쪽 상단의 언어 선택 드롭다운 메뉴를 사용하여 다음 예제의 언어 설정하다 하거나 MongoDB Shell 선택합니다.
이 예제에서는 두 개의 collection을 사용합니다:
products
, 상점에서 판매하는 제품을 설명하는 문서가 포함되어 있습니다.orders
, 상점의 제품에 대한 개별 주문을 설명하는 문서가 포함되어 있습니다.
주문에는 하나의 제품만 포함될 수 있습니다. 집계 다중 필드 조인을 사용하여 제품 문서 해당 제품의 주문을 나타내는 문서와 일치시킵니다. 집계 orders
컬렉션 문서의 product_name
및 product_variation
필드에 해당하는 products
컬렉션 문서의 name
및 variation
필드를 기준으로 컬렉션을 조인합니다.
및 컬렉션을 만들려면 orders
products
메서드를 insertMany()
사용합니다.
db.orders.deleteMany({}) db.orders.insertMany( [ { customer_id: "[email protected]", orderdate: new Date("2020-05-30T08:35:52Z"), product_name: "Asus Laptop", product_variation: "Standard Display", value: 431.43, }, { customer_id: "[email protected]", orderdate: new Date("2019-05-28T19:13:32Z"), product_name: "The Day Of The Triffids", product_variation: "2nd Edition", value: 5.01, }, { customer_id: "[email protected]", orderdate: new Date("2020-01-01T08:25:37Z"), product_name: "Morphy Richards Food Mixer", product_variation: "Deluxe", value: 63.13, }, { customer_id: "[email protected]", orderdate: new Date("2020-12-26T08:55:46Z"), product_name: "Asus Laptop", product_variation: "Standard Display", value: 429.65, } ] )
db.products.deleteMany({}) db.products.insertMany( [ { name: "Asus Laptop", variation: "Ultra HD", category: "ELECTRONICS", description: "Great for watching movies" }, { name: "Asus Laptop", variation: "Standard Display", category: "ELECTRONICS", description: "Good value laptop for students" }, { name: "The Day Of The Triffids", variation: "1st Edition", category: "BOOKS", description: "Classic post-apocalyptic novel" }, { name: "The Day Of The Triffids", variation: "2nd Edition", category: "BOOKS", description: "Classic post-apocalyptic novel" }, { name: "Morphy Richards Food Mixer", variation: "Deluxe", category: "KITCHENWARE", description: "Luxury mixer turning good cakes into great" } ] )
템플릿 앱 만들기
이 집계 튜토리얼을 시작하기 전에 새 C 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .
팁
운전자 설치하고 MongoDB 에 연결하는 방법을 학습 C 드라이버 시작하기 가이드 참조하세요.
C 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드 참조하세요.
운전자 설치한 후 agg-tutorial.c
라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.
중요
다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.
변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.
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";
컬렉션 생성
이 예제에서는 두 개의 collection을 사용합니다:
products
, 상점에서 판매하는 제품을 설명하는 문서가 포함되어 있습니다.orders
, 상점의 제품에 대한 개별 주문을 설명하는 문서가 포함되어 있습니다.
주문에는 하나의 제품만 포함될 수 있습니다. 집계 다중 필드 조인을 사용하여 제품 문서 해당 제품의 주문을 나타내는 문서와 일치시킵니다. 집계 orders
컬렉션 문서의 product_name
및 product_variation
필드에 해당하는 products
컬렉션 문서의 name
및 variation
필드를 기준으로 컬렉션을 조인합니다.
products
및 orders
컬렉션을 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.
mongoc_collection_t *products = mongoc_client_get_collection(client, "agg_tutorials_db", "products"); 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(products, filter, NULL, NULL, &error)) { fprintf(stderr, "Delete error: %s\n", error.message); } 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 = 5; bson_t *product_docs[num_docs]; product_docs[0] = BCON_NEW( "name", BCON_UTF8("Asus Laptop"), "variation", BCON_UTF8("Ultra HD"), "category", BCON_UTF8("ELECTRONICS"), "description", BCON_UTF8("Great for watching movies")); product_docs[1] = BCON_NEW( "name", BCON_UTF8("Asus Laptop"), "variation", BCON_UTF8("Standard Display"), "category", BCON_UTF8("ELECTRONICS"), "description", BCON_UTF8("Good value laptop for students")); product_docs[2] = BCON_NEW( "name", BCON_UTF8("The Day Of The Triffids"), "variation", BCON_UTF8("1st Edition"), "category", BCON_UTF8("BOOKS"), "description", BCON_UTF8("Classic post-apocalyptic novel")); product_docs[3] = BCON_NEW( "name", BCON_UTF8("The Day Of The Triffids"), "variation", BCON_UTF8("2nd Edition"), "category", BCON_UTF8("BOOKS"), "description", BCON_UTF8("Classic post-apocalyptic novel")); product_docs[4] = BCON_NEW( "name", BCON_UTF8("Morphy Richards Food Mixer"), "variation", BCON_UTF8("Deluxe"), "category", BCON_UTF8("KITCHENWARE"), "description", BCON_UTF8("Luxury mixer turning good cakes into great")); bson_error_t error; if (!mongoc_collection_insert_many(products, (const bson_t **)product_docs, num_docs, NULL, NULL, &error)) { fprintf(stderr, "Insert error: %s\n", error.message); } for (int i = 0; i < num_docs; i++) { bson_destroy(product_docs[i]); } } { size_t num_docs = 4; bson_t *order_docs[num_docs]; order_docs[0] = BCON_NEW( "customer_id", BCON_UTF8("[email protected]"), "orderdate", BCON_DATE_TIME(1590822952000UL), // 2020-05-30T08:35:52Z "product_name", BCON_UTF8("Asus Laptop"), "product_variation", BCON_UTF8("Standard Display"), "value", BCON_DOUBLE(431.43)); order_docs[1] = BCON_NEW( "customer_id", BCON_UTF8("[email protected]"), "orderdate", BCON_DATE_TIME(1559063612000UL), // 2019-05-28T19:13:32Z "product_name", BCON_UTF8("The Day Of The Triffids"), "product_variation", BCON_UTF8("2nd Edition"), "value", BCON_DOUBLE(5.01)); order_docs[2] = BCON_NEW( "customer_id", BCON_UTF8("[email protected]"), "orderdate", BCON_DATE_TIME(1577869537000UL), // 2020-01-01T08:25:37Z "product_name", BCON_UTF8("Morphy Richards Food Mixer"), "product_variation", BCON_UTF8("Deluxe"), "value", BCON_DOUBLE(63.13)); order_docs[3] = BCON_NEW( "customer_id", BCON_UTF8("[email protected]"), "orderdate", BCON_DATE_TIME(1608976546000UL), // 2020-12-26T08:55:46Z "product_name", BCON_UTF8("Asus Laptop"), "product_variation", BCON_UTF8("Standard Display"), "value", BCON_DOUBLE(429.65)); bson_error_t error; if (!mongoc_collection_insert_many(orders, (const bson_t **)order_docs, num_docs, NULL, NULL, &error)) { fprintf(stderr, "Insert error: %s\n", error.message); } for (int i = 0; i < num_docs; i++) { bson_destroy(order_docs[i]); } }
템플릿 앱 만들기
집계 튜토리얼을 따라 하기 전에 새 C++ 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .
팁
운전자 설치하고 MongoDB 에 연결하는 방법을 학습 C++ 시작하기 튜토리얼을 참조하세요.
C++ 운전자 사용에 대해 자세히 학습 API 설명서를 참조하세요.
C++ 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드 참조하세요.
운전자 설치한 후 agg-tutorial.cpp
라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.
중요
다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.
변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.
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; } }
모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.
예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017"
인 경우 연결 문자열 할당은 다음과 유사합니다.
mongocxx::uri uri{"mongodb+srv://mongodb-example:27017"};
컬렉션 생성
이 예제에서는 두 개의 collection을 사용합니다:
products
, 상점에서 판매하는 제품을 설명하는 문서가 포함되어 있습니다.orders
, 상점의 제품에 대한 개별 주문을 설명하는 문서가 포함되어 있습니다.
주문에는 하나의 제품만 포함될 수 있습니다. 집계 다중 필드 조인을 사용하여 제품 문서 해당 제품의 주문을 나타내는 문서와 일치시킵니다. 집계 orders
컬렉션 문서의 product_name
및 product_variation
필드에 해당하는 products
컬렉션 문서의 name
및 variation
필드를 기준으로 컬렉션을 조인합니다.
products
및 orders
컬렉션을 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.
auto products = db["products"]; auto orders = db["orders"]; std::vector<bsoncxx::document::value> product_docs = { bsoncxx::from_json(R"({ "name": "Asus Laptop", "variation": "Ultra HD", "category": "ELECTRONICS", "description": "Great for watching movies" })"), bsoncxx::from_json(R"({ "name": "Asus Laptop", "variation": "Standard Display", "category": "ELECTRONICS", "description": "Good value laptop for students" })"), bsoncxx::from_json(R"({ "name": "The Day Of The Triffids", "variation": "1st Edition", "category": "BOOKS", "description": "Classic post-apocalyptic novel" })"), bsoncxx::from_json(R"({ "name": "The Day Of The Triffids", "variation": "2nd Edition", "category": "BOOKS", "description": "Classic post-apocalyptic novel" })"), bsoncxx::from_json(R"({ "name": "Morphy Richards Food Mixer", "variation": "Deluxe", "category": "KITCHENWARE", "description": "Luxury mixer turning good cakes into great" })") }; products.insert_many(product_docs); // Might throw an exception std::vector<bsoncxx::document::value> order_docs = { bsoncxx::from_json(R"({ "customer_id": "[email protected]", "orderdate": {"$date": 1590821752000}, "product_name": "Asus Laptop", "product_variation": "Standard Display", "value": 431.43 })"), bsoncxx::from_json(R"({ "customer_id": "[email protected]", "orderdate": {"$date": 1559062412000}, "product_name": "The Day Of The Triffids", "product_variation": "2nd Edition", "value": 5.01 })"), bsoncxx::from_json(R"({ "customer_id": "[email protected]", "orderdate": {"$date": 1577861137000}, "product_name": "Morphy Richards Food Mixer", "product_variation": "Deluxe", "value": 63.13 })"), bsoncxx::from_json(R"({ "customer_id": "[email protected]", "orderdate": {"$date": 1608972946000}, "product_name": "Asus Laptop", "product_variation": "Standard Display", "value": 429.65 })") }; 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";
컬렉션 생성
이 예제에서는 두 개의 collection을 사용합니다:
products
, 상점에서 판매하는 제품을 설명하는 문서가 포함되어 있습니다.orders
, 상점의 제품에 대한 개별 주문을 설명하는 문서가 포함되어 있습니다.
주문에는 하나의 제품만 포함될 수 있습니다. 집계 다중 필드 조인을 사용하여 제품 문서 해당 제품의 주문을 나타내는 문서와 일치시킵니다. 집계 orders
컬렉션 문서의 ProductName
및 ProductVariation
필드에 해당하는 products
컬렉션 문서의 Name
및 Variation
필드를 기준으로 컬렉션을 조인합니다.
먼저 C# 클래스를 만들어 products
및 orders
컬렉션의 데이터를 모델링합니다.
public class Product { [ ] public ObjectId Id { get; set; } public string Name { get; set; } public string Variation { get; set; } public string Category { get; set; } public string Description { get; set; } } public class Order { [ ] public ObjectId Id { get; set; } public string CustomerId { get; set; } public DateTime OrderDate { get; set; } public string ProductName { get; set; } public string ProductVariation { get; set; } public double Value { get; set; } }
products
및 orders
컬렉션을 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.
var products = aggDB.GetCollection<Product>("products"); var orders = aggDB.GetCollection<Order>("orders"); products.DeleteMany(Builders<Product>.Filter.Empty); orders.DeleteMany(Builders<Order>.Filter.Empty); products.InsertMany(new List<Product> { new Product { Name = "Asus Laptop", Variation = "Ultra HD", Category = "ELECTRONICS", Description = "Great for watching movies" }, new Product { Name = "Asus Laptop", Variation = "Standard Display", Category = "ELECTRONICS", Description = "Good value laptop for students" }, new Product { Name = "The Day Of The Triffids", Variation = "1st Edition", Category = "BOOKS", Description = "Classic post-apocalyptic novel" }, new Product { Name = "The Day Of The Triffids", Variation = "2nd Edition", Category = "BOOKS", Description = "Classic post-apocalyptic novel" }, new Product { Name = "Morphy Richards Food Mixer", Variation = "Deluxe", Category = "KITCHENWARE", Description = "Luxury mixer turning good cakes into great" } }); orders.InsertMany(new List<Order> { new Order { CustomerId = "[email protected]", OrderDate = DateTime.Parse("2020-05-30T08:35:52Z"), ProductName = "Asus Laptop", ProductVariation = "Standard Display", Value = 431.43 }, new Order { CustomerId = "[email protected]", OrderDate = DateTime.Parse("2019-05-28T19:13:32Z"), ProductName = "The Day Of The Triffids", ProductVariation = "2nd Edition", Value = 5.01 }, new Order { CustomerId = "[email protected]", OrderDate = DateTime.Parse("2020-01-01T08:25:37Z"), ProductName = "Morphy Richards Food Mixer", ProductVariation = "Deluxe", Value = 63.13 }, new Order { CustomerId = "[email protected]", OrderDate = DateTime.Parse("2020-12-26T08:55:46Z"), ProductName = "Asus Laptop", ProductVariation = "Standard Display", Value = 429.65 } });
템플릿 앱 만들기
이 집계 튜토리얼을 시작하기 전에 새 고 (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";
컬렉션 생성
이 예제에서는 두 개의 collection을 사용합니다:
products
, 상점에서 판매하는 제품을 설명하는 문서가 포함되어 있습니다.orders
, 상점의 제품에 대한 개별 주문을 설명하는 문서가 포함되어 있습니다.
주문에는 하나의 제품만 포함될 수 있습니다. 집계 다중 필드 조인을 사용하여 제품 문서 해당 제품의 주문을 나타내는 문서와 일치시킵니다. 집계 orders
컬렉션 문서의 product_name
및 product_variation
필드에 해당하는 products
컬렉션 문서의 name
및 variation
필드를 기준으로 컬렉션을 조인합니다.
먼저 고 (Go) 구조체를 만들어 products
및 orders
컬렉션의 데이터를 모델링합니다.
type Product struct { Name string Variation string Category string Description string } type Order struct { CustomerID string `bson:"customer_id"` OrderDate bson.DateTime `bson:"orderdate"` ProductName string `bson:"product_name"` ProductVariation string `bson:"product_variation"` Value float32 `bson:"value"` }
products
및 orders
컬렉션을 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.
products := aggDB.Collection("products") orders := aggDB.Collection("orders") products.DeleteMany(context.TODO(), bson.D{}) orders.DeleteMany(context.TODO(), bson.D{}) _, err = products.InsertMany(context.TODO(), []interface{}{ Product{ Name: "Asus Laptop", Variation: "Ultra HD", Category: "ELECTRONICS", Description: "Great for watching movies", }, Product{ Name: "Asus Laptop", Variation: "Standard Display", Category: "ELECTRONICS", Description: "Good value laptop for students", }, Product{ Name: "The Day Of The Triffids", Variation: "1st Edition", Category: "BOOKS", Description: "Classic post-apocalyptic novel", }, Product{ Name: "The Day Of The Triffids", Variation: "2nd Edition", Category: "BOOKS", Description: "Classic post-apocalyptic novel", }, Product{ Name: "Morphy Richards Food Mixer", Variation: "Deluxe", Category: "KITCHENWARE", Description: "Luxury mixer turning good cakes into great", }, }) if err != nil { log.Fatal(err) } _, err = orders.InsertMany(context.TODO(), []interface{}{ Order{ CustomerID: "[email protected]", OrderDate: bson.NewDateTimeFromTime(time.Date(2020, 5, 30, 8, 35, 52, 0, time.UTC)), ProductName: "Asus Laptop", ProductVariation: "Standard Display", Value: 431.43, }, Order{ CustomerID: "[email protected]", OrderDate: bson.NewDateTimeFromTime(time.Date(2019, 5, 28, 19, 13, 32, 0, time.UTC)), ProductName: "The Day Of The Triffids", ProductVariation: "2nd Edition", Value: 5.01, }, Order{ CustomerID: "[email protected]", OrderDate: bson.NewDateTimeFromTime(time.Date(2020, 1, 1, 8, 25, 37, 0, time.UTC)), ProductName: "Morphy Richards Food Mixer", ProductVariation: "Deluxe", Value: 63.13, }, Order{ CustomerID: "[email protected]", OrderDate: bson.NewDateTimeFromTime(time.Date(2020, 12, 26, 8, 55, 46, 0, time.UTC)), ProductName: "Asus Laptop", ProductVariation: "Standard Display", Value: 429.65, }, }) 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";
컬렉션 생성
이 예제에서는 두 개의 collection을 사용합니다:
products
, 상점에서 판매하는 제품을 설명하는 문서가 포함되어 있습니다.orders
, 상점의 제품에 대한 개별 주문을 설명하는 문서가 포함되어 있습니다.
주문에는 하나의 제품만 포함될 수 있습니다. 집계 다중 필드 조인을 사용하여 제품 문서 해당 제품의 주문을 나타내는 문서와 일치시킵니다. 집계 orders
컬렉션 문서의 product_name
및 product_variation
필드에 해당하는 products
컬렉션 문서의 name
및 variation
필드를 기준으로 컬렉션을 조인합니다.
products
및 orders
컬렉션을 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.
MongoCollection<Document> products = aggDB.getCollection("products"); MongoCollection<Document> orders = aggDB.getCollection("orders"); products.deleteMany(Filters.empty()); orders.deleteMany(Filters.empty()); products.insertMany( Arrays.asList( new Document("name", "Asus Laptop") .append("variation", "Ultra HD") .append("category", "ELECTRONICS") .append("description", "Great for watching movies"), new Document("name", "Asus Laptop") .append("variation", "Standard Display") .append("category", "ELECTRONICS") .append("description", "Good value laptop for students"), new Document("name", "The Day Of The Triffids") .append("variation", "1st Edition") .append("category", "BOOKS") .append("description", "Classic post-apocalyptic novel"), new Document("name", "The Day Of The Triffids") .append("variation", "2nd Edition") .append("category", "BOOKS") .append("description", "Classic post-apocalyptic novel"), new Document("name", "Morphy Richards Food Mixer") .append("variation", "Deluxe") .append("category", "KITCHENWARE") .append("description", "Luxury mixer turning good cakes into great") ) ); orders.insertMany( Arrays.asList( new Document("customer_id", "[email protected]") .append("orderdate", LocalDateTime.parse("2020-05-30T08:35:52")) .append("product_name", "Asus Laptop") .append("product_variation", "Standard Display") .append("value", 431.43), new Document("customer_id", "[email protected]") .append("orderdate", LocalDateTime.parse("2019-05-28T19:13:32")) .append("product_name", "The Day Of The Triffids") .append("product_variation", "2nd Edition") .append("value", 5.01), new Document("customer_id", "[email protected]") .append("orderdate", LocalDateTime.parse("2020-01-01T08:25:37")) .append("product_name", "Morphy Richards Food Mixer") .append("product_variation", "Deluxe") .append("value", 63.13), new Document("customer_id", "[email protected]") .append("orderdate", LocalDateTime.parse("2020-12-26T08:55:46")) .append("product_name", "Asus Laptop") .append("product_variation", "Standard Display") .append("value", 429.65) ) );
템플릿 앱 만들기
집계 튜토리얼을 시작하기 전에 새 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";
컬렉션 생성
이 예제에서는 두 개의 collection을 사용합니다:
products
, 상점에서 판매하는 제품을 설명하는 문서가 포함되어 있습니다.orders
, 상점의 제품에 대한 개별 주문을 설명하는 문서가 포함되어 있습니다.
주문에는 하나의 제품만 포함될 수 있습니다. 집계 다중 필드 조인을 사용하여 제품 문서 해당 제품의 주문을 나타내는 문서와 일치시킵니다. 집계 orders
컬렉션 문서의 product_name
및 product_variation
필드에 해당하는 products
컬렉션 문서의 name
및 variation
필드를 기준으로 컬렉션을 조인합니다.
먼저 코틀린 (Kotlin) 데이터 클래스를 만들어 products
및 orders
컬렉션의 데이터를 모델링합니다.
data class Product( val name: String, val variation: String, val category: String, val description: String ) data class Order( val customerID: String, val orderDate: LocalDateTime, val productName: String, val productVariation: String, val value: Double )
products
및 orders
컬렉션을 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.
val products = aggDB.getCollection<Product>("products") val orders = aggDB.getCollection<Order>("orders") products.deleteMany(Filters.empty()); orders.deleteMany(Filters.empty()); products.insertMany( listOf( Product("Asus Laptop", "Ultra HD", "ELECTRONICS", "Great for watching movies"), Product("Asus Laptop", "Standard Display", "ELECTRONICS", "Good value laptop for students"), Product("The Day Of The Triffids", "1st Edition", "BOOKS", "Classic post-apocalyptic novel"), Product("The Day Of The Triffids", "2nd Edition", "BOOKS", "Classic post-apocalyptic novel"), Product( "Morphy Richards Food Mixer", "Deluxe", "KITCHENWARE", "Luxury mixer turning good cakes into great" ) ) ) orders.insertMany( listOf( Order( "[email protected]", LocalDateTime.parse("2020-05-30T08:35:52"), "Asus Laptop", "Standard Display", 431.43 ), Order( "[email protected]", LocalDateTime.parse("2019-05-28T19:13:32"), "The Day Of The Triffids", "2nd Edition", 5.01 ), Order( "[email protected]", LocalDateTime.parse("2020-01-01T08:25:37"), "Morphy Richards Food Mixer", "Deluxe", 63.13 ), Order( "[email protected]", LocalDateTime.parse("2020-12-26T08:55:46"), "Asus Laptop", "Standard Display", 429.65 ) ) )
템플릿 앱 만들기
이 집계 튜토리얼을 따라 시작하기 전에 새 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);
모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.
예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017"
인 경우 연결 문자열 할당은 다음과 유사합니다.
const uri = "mongodb+srv://mongodb-example:27017";
컬렉션 생성
이 예제에서는 두 개의 collection을 사용합니다:
products
, 상점에서 판매하는 제품을 설명하는 문서가 포함되어 있습니다.orders
, 상점의 제품에 대한 개별 주문을 설명하는 문서가 포함되어 있습니다.
주문에는 하나의 제품만 포함될 수 있습니다. 집계 다중 필드 조인을 사용하여 제품 문서 해당 제품의 주문을 나타내는 문서와 일치시킵니다. 집계 orders
컬렉션 문서의 product_name
및 product_variation
필드에 해당하는 products
컬렉션 문서의 name
및 variation
필드를 기준으로 컬렉션을 조인합니다.
products
및 orders
컬렉션을 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.
const products = aggDB.collection("products"); const orders = aggDB.collection("orders"); await products.deleteMany({}); await orders.deleteMany({}); await products.insertMany([ { name: "Asus Laptop", variation: "Ultra HD", category: "ELECTRONICS", description: "Great for watching movies", }, { name: "Asus Laptop", variation: "Standard Display", category: "ELECTRONICS", description: "Good value laptop for students", }, { name: "The Day Of The Triffids", variation: "1st Edition", category: "BOOKS", description: "Classic post-apocalyptic novel", }, { name: "The Day Of The Triffids", variation: "2nd Edition", category: "BOOKS", description: "Classic post-apocalyptic novel", }, { name: "Morphy Richards Food Mixer", variation: "Deluxe", category: "KITCHENWARE", description: "Luxury mixer turning good cakes into great", }, ]); await orders.insertMany([ { customer_id: "[email protected]", orderdate: new Date("2020-05-30T08:35:52Z"), product_name: "Asus Laptop", product_variation: "Standard Display", value: 431.43, }, { customer_id: "[email protected]", orderdate: new Date("2019-05-28T19:13:32Z"), product_name: "The Day Of The Triffids", product_variation: "2nd Edition", value: 5.01, }, { customer_id: "[email protected]", orderdate: new Date("2020-01-01T08:25:37Z"), product_name: "Morphy Richards Food Mixer", product_variation: "Deluxe", value: 63.13, }, { customer_id: "[email protected]", orderdate: new Date("2020-12-26T08:55:46Z"), product_name: "Asus Laptop", product_variation: "Standard Display", value: 429.65, }, ]);
템플릿 앱 만들기
이 집계 튜토리얼을 시작하기 전에 새 고 (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";
컬렉션 생성
이 예제에서는 두 개의 collection을 사용합니다:
products
, 상점에서 판매하는 제품을 설명하는 문서가 포함되어 있습니다.orders
, 상점의 제품에 대한 개별 주문을 설명하는 문서가 포함되어 있습니다.
주문에는 하나의 제품만 포함될 수 있습니다. 집계 다중 필드 조인을 사용하여 제품 문서 해당 제품의 주문을 나타내는 문서와 일치시킵니다. 집계 orders
컬렉션 문서의 product_name
및 product_variation
필드에 해당하는 products
컬렉션 문서의 name
및 variation
필드를 기준으로 컬렉션을 조인합니다.
products
및 orders
컬렉션을 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.
$products = $client->agg_tutorials_db->products; $orders = $client->agg_tutorials_db->orders; $products->deleteMany([]); $orders->deleteMany([]); $products->insertMany( [ [ 'name' => "Asus Laptop", 'variation' => "Ultra HD", 'category' => "ELECTRONICS", 'description' => "Great for watching movies" ], [ 'name' => "Asus Laptop", 'variation' => "Standard Display", 'category' => "ELECTRONICS", 'description' => "Good value laptop for students" ], [ 'name' => "The Day Of The Triffids", 'variation' => "1st Edition", 'category' => "BOOKS", 'description' => "Classic post-apocalyptic novel" ], [ 'name' => "The Day Of The Triffids", 'variation' => "2nd Edition", 'category' => "BOOKS", 'description' => "Classic post-apocalyptic novel" ], [ 'name' => "Morphy Richards Food Mixer", 'variation' => "Deluxe", 'category' => "KITCHENWARE", 'description' => "Luxury mixer turning good cakes into great" ] ] ); $orders->insertMany( [ [ 'customer_id' => "[email protected]", 'orderdate' => new UTCDateTime((new DateTimeImmutable("2020-05-30T08:35:52"))), 'product_name' => "Asus Laptop", 'product_variation' => "Standard Display", 'value' => 431.43 ], [ 'customer_id' => "[email protected]", 'orderdate' => new UTCDateTime((new DateTimeImmutable("2019-05-28T19:13:32"))), 'product_name' => "The Day Of The Triffids", 'product_variation' => "2nd Edition", 'value' => 5.01 ], [ 'customer_id' => "[email protected]", 'orderdate' => new UTCDateTime((new DateTimeImmutable("2020-01-01T08:25:37"))), 'product_name' => "Morphy Richards Food Mixer", 'product_variation' => "Deluxe", 'value' => 63.13 ], [ 'customer_id' => "[email protected]", 'orderdate' => new UTCDateTime((new DateTimeImmutable("2020-12-26T08:55:46"))), 'product_name' => "Asus Laptop", 'product_variation' => "Standard Display", 'value' => 429.65 ] ] );
템플릿 앱 만들기
이 집계 튜토리얼을 따라 시작하기 전에 새 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"
컬렉션 생성
이 예제에서는 두 개의 collection을 사용합니다:
products
, 상점에서 판매하는 제품을 설명하는 문서가 포함되어 있습니다.orders
, 상점의 제품에 대한 개별 주문을 설명하는 문서가 포함되어 있습니다.
주문에는 하나의 제품만 포함될 수 있습니다. 집계 다중 필드 조인을 사용하여 제품 문서 해당 제품의 주문을 나타내는 문서와 일치시킵니다. 집계 orders
컬렉션 문서의 product_name
및 product_variation
필드에 해당하는 products
컬렉션 문서의 name
및 variation
필드를 기준으로 컬렉션을 조인합니다.
products
및 orders
컬렉션을 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.
products_coll = agg_db["products"] orders_coll = agg_db["orders"] products_coll.delete_many({}) products_data = [ { "name": "Asus Laptop", "variation": "Ultra HD", "category": "ELECTRONICS", "description": "Great for watching movies", }, { "name": "Asus Laptop", "variation": "Standard Display", "category": "ELECTRONICS", "description": "Good value laptop for students", }, { "name": "The Day Of The Triffids", "variation": "1st Edition", "category": "BOOKS", "description": "Classic post-apocalyptic novel", }, { "name": "The Day Of The Triffids", "variation": "2nd Edition", "category": "BOOKS", "description": "Classic post-apocalyptic novel", }, { "name": "Morphy Richards Food Mixer", "variation": "Deluxe", "category": "KITCHENWARE", "description": "Luxury mixer turning good cakes into great", }, ] products_coll.insert_many(products_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
모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.
예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017"
인 경우 연결 문자열 할당은 다음과 유사합니다.
uri = "mongodb+srv://mongodb-example:27017"
컬렉션 생성
이 예제에서는 두 개의 collection을 사용합니다:
products
, 상점에서 판매하는 제품을 설명하는 문서가 포함되어 있습니다.orders
, 상점의 제품에 대한 개별 주문을 설명하는 문서가 포함되어 있습니다.
주문에는 하나의 제품만 포함될 수 있습니다. 집계 다중 필드 조인을 사용하여 제품 문서 해당 제품의 주문을 나타내는 문서와 일치시킵니다. 집계 orders
컬렉션 문서의 product_name
및 product_variation
필드에 해당하는 products
컬렉션 문서의 name
및 variation
필드를 기준으로 컬렉션을 조인합니다.
products
및 orders
컬렉션을 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.
products = agg_db[:products] orders = agg_db[:orders] products.delete_many({}) orders.delete_many({}) products.insert_many( [ { name: "Asus Laptop", variation: "Ultra HD", category: "ELECTRONICS", description: "Great for watching movies", }, { name: "Asus Laptop", variation: "Standard Display", category: "ELECTRONICS", description: "Good value laptop for students", }, { name: "The Day Of The Triffids", variation: "1st Edition", category: "BOOKS", description: "Classic post-apocalyptic novel", }, { name: "The Day Of The Triffids", variation: "2nd Edition", category: "BOOKS", description: "Classic post-apocalyptic novel", }, { name: "Morphy Richards Food Mixer", variation: "Deluxe", category: "KITCHENWARE", description: "Luxury mixer turning good cakes into great", }, ] ) orders.insert_many( [ { customer_id: "[email protected]", orderdate: DateTime.parse("2020-05-30T08:35:52Z"), product_name: "Asus Laptop", product_variation: "Standard Display", value: 431.43, }, { customer_id: "[email protected]", orderdate: DateTime.parse("2019-05-28T19:13:32Z"), product_name: "The Day Of The Triffids", product_variation: "2nd Edition", value: 5.01, }, { customer_id: "[email protected]", orderdate: DateTime.parse("2020-01-01T08:25:37Z"), product_name: "Morphy Richards Food Mixer", product_variation: "Deluxe", value: 63.13, }, { customer_id: "[email protected]", orderdate: DateTime.parse("2020-12-26T08:55:46Z"), product_name: "Asus Laptop", product_variation: "Standard Display", value: 429.65, }, ] )
템플릿 앱 만들기
이 집계 튜토리얼을 시작하기 전에 새 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 { ... } 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";
컬렉션 생성
이 예제에서는 두 개의 collection을 사용합니다:
products
, 상점에서 판매하는 제품을 설명하는 문서가 포함되어 있습니다.orders
, 상점의 제품에 대한 개별 주문을 설명하는 문서가 포함되어 있습니다.
주문에는 하나의 제품만 포함될 수 있습니다. 집계 다중 필드 조인을 사용하여 제품 문서 해당 제품의 주문을 나타내는 문서와 일치시킵니다. 집계 orders
컬렉션 문서의 product_name
및 product_variation
필드에 해당하는 products
컬렉션 문서의 name
및 variation
필드를 기준으로 컬렉션을 조인합니다.
먼저 Rust 구조체를 만들어 products
및 orders
컬렉션의 데이터를 모델링합니다.
struct Product { name: String, variation: String, category: String, description: String, } struct Order { customer_id: String, order_date: DateTime, product_name: String, product_variation: String, value: f32, }
products
및 orders
컬렉션을 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.
let products: Collection<Product> = agg_db.collection("products"); let orders: Collection<Order> = agg_db.collection("orders"); products.delete_many(doc! {}).await?; orders.delete_many(doc! {}).await?; let product_docs = vec![ Product { name: "Asus Laptop".to_string(), variation: "Ultra HD".to_string(), category: "ELECTRONICS".to_string(), description: "Great for watching movies".to_string(), }, Product { name: "Asus Laptop".to_string(), variation: "Standard Display".to_string(), category: "ELECTRONICS".to_string(), description: "Good value laptop for students".to_string(), }, Product { name: "The Day Of The Triffids".to_string(), variation: "1st Edition".to_string(), category: "BOOKS".to_string(), description: "Classic post-apocalyptic novel".to_string(), }, Product { name: "The Day Of The Triffids".to_string(), variation: "2nd Edition".to_string(), category: "BOOKS".to_string(), description: "Classic post-apocalyptic novel".to_string(), }, Product { name: "Morphy Richards Food Mixer".to_string(), variation: "Deluxe".to_string(), category: "KITCHENWARE".to_string(), description: "Luxury mixer turning good cakes into great".to_string(), }, ]; products.insert_many(product_docs).await?; let order_docs = vec![ Order { customer_id: "[email protected]".to_string(), order_date: DateTime::builder().year(2020).month(5).day(30).hour(8).minute(35).second(52).build().unwrap(), product_name: "Asus Laptop".to_string(), product_variation: "Standard Display".to_string(), value: 431.43, }, Order { customer_id: "[email protected]".to_string(), order_date: DateTime::builder().year(2019).month(5).day(28).hour(19).minute(13).second(32).build().unwrap(), product_name: "The Day Of The Triffids".to_string(), product_variation: "2nd Edition".to_string(), value: 5.01, }, Order { customer_id: "[email protected]".to_string(), order_date: DateTime::builder().year(2020).month(1).day(1).hour(8).minute(25).second(37).build().unwrap(), product_name: "Morphy Richards Food Mixer".to_string(), product_variation: "Deluxe".to_string(), value: 63.13, }, Order { customer_id: "[email protected]".to_string(), order_date: DateTime::builder().year(2020).month(12).day(26).hour(8).minute(55).second(46).build().unwrap(), product_name: "Asus Laptop".to_string(), product_variation: "Standard Display".to_string(), value: 429.65, }, ]; orders.insert_many(order_docs).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"
컬렉션 생성
이 예제에서는 두 개의 collection을 사용합니다:
products
, 상점에서 판매하는 제품을 설명하는 문서가 포함되어 있습니다.orders
, 상점의 제품에 대한 개별 주문을 설명하는 문서가 포함되어 있습니다.
주문에는 하나의 제품만 포함될 수 있습니다. 집계 다중 필드 조인을 사용하여 제품 문서 해당 제품의 주문을 나타내는 문서와 일치시킵니다. 집계 orders
컬렉션 문서의 product_name
및 product_variation
필드에 해당하는 products
컬렉션 문서의 name
및 variation
필드를 기준으로 컬렉션을 조인합니다.
products
및 orders
컬렉션을 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.
val products = aggDB.getCollection("products") val orders = aggDB.getCollection("orders") products.deleteMany(Filters.empty()).subscribe( _ => {}, e => println("Error: " + e.getMessage), ) orders.deleteMany(Filters.empty()).subscribe( _ => {}, e => println("Error: " + e.getMessage), ) val dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss") products.insertMany( Seq( Document( "name" -> "Asus Laptop", "variation" -> "Ultra HD", "category" -> "ELECTRONICS", "description" -> "Great for watching movies" ), Document( "name" -> "Asus Laptop", "variation" -> "Standard Display", "category" -> "ELECTRONICS", "description" -> "Good value laptop for students" ), Document( "name" -> "The Day Of The Triffids", "variation" -> "1st Edition", "category" -> "BOOKS", "description" -> "Classic post-apocalyptic novel" ), Document( "name" -> "The Day Of The Triffids", "variation" -> "2nd Edition", "category" -> "BOOKS", "description" -> "Classic post-apocalyptic novel" ), Document( "name" -> "Morphy Richards Food Mixer", "variation" -> "Deluxe", "category" -> "KITCHENWARE", "description" -> "Luxury mixer turning good cakes into great" ) ) ).subscribe( _ => {}, e => println("Error: " + e.getMessage), ) orders.insertMany( Seq( Document( "customer_id" -> "[email protected]", "orderdate" -> dateFormat.parse("2020-05-30T08:35:52"), "product_name" -> "Asus Laptop", "product_variation" -> "Standard Display", "value" -> 431.43 ), Document( "customer_id" -> "[email protected]", "orderdate" -> dateFormat.parse("2019-05-28T19:13:32"), "product_name" -> "The Day Of The Triffids", "product_variation" -> "2nd Edition", "value" -> 5.01 ), Document( "customer_id" -> "[email protected]", "orderdate" -> dateFormat.parse("2020-01-01T08:25:37"), "product_name" -> "Morphy Richards Food Mixer", "product_variation" -> "Deluxe", "value" -> 63.13 ), Document( "customer_id" -> "[email protected]", "orderdate" -> dateFormat.parse("2020-12-26T08:55:46"), "product_name" -> "Asus Laptop", "product_variation" -> "Standard Display", "value" -> 429.65 ) ) ).subscribe( _ => {}, e => println("Error: " + e.getMessage), )
단계
다음 단계에서는 집계 파이프라인 만들고 실행 여러 필드의 컬렉션을 조인하는 방법을 보여 줍니다.
조회 단계에서 사용할 임베디드 파이프라인 만듭니다.
파이프라인 의 첫 번째 단계는 각 컬렉션 의 두 필드를 기준으로 orders
컬렉션 products
컬렉션 에 조인하는 $lookup
단계입니다. $lookup
단계에는 조인을 구성하기 위한 파이프라인 포함되어 있습니다.
embedded_pl = [ // Stage 1: Match the values of two fields on each side of the join // The $eq filter uses aliases for the name and variation fields set { $match: { $expr: { $and: [ { $eq: ["$product_name", "$$prdname"] }, { $eq: ["$product_variation", "$$prdvartn"] } ] } } }, // Stage 2: Match orders placed in 2020 { $match: { orderdate: { $gte: new Date("2020-01-01T00:00:00Z"), $lt: new Date("2021-01-01T00:00:00Z") } } }, // Stage 3: Remove unneeded fields from the orders collection side of the join { $unset: ["_id", "product_name", "product_variation"] } ]
집계 파이프라인 실행합니다.
db.products.aggregate( [ // Use the embedded pipeline in a lookup stage { $lookup: { from: "orders", let: { prdname: "$name", prdvartn: "$variation" }, pipeline: embedded_pl, as: "orders" } }, // Match products ordered in 2020 { $match: { orders: { $ne: [] } } }, // Remove unneeded fields { $unset: ["_id", "description"] } ] )
집계 결과를 해석합니다.
애그리게이션된 결과에는 두 개의 문서가 포함됩니다. 문서는 2020을(를) 주문한 제품을 나타냅니다. 각 문서 에는 해당 제품의 각 주문에 대한 세부 정보를 나열하는 orders
배열 필드 포함되어 있습니다.
{ name: 'Asus Laptop', variation: 'Standard Display', category: 'ELECTRONICS', orders: [ { customer_id: '[email protected]', orderdate: ISODate('2020-05-30T08:35:52.000Z'), value: 431.43 }, { customer_id: '[email protected]', orderdate: ISODate('2020-12-26T08:55:46.000Z'), value: 429.65 } ] } { name: 'Morphy Richards Food Mixer', variation: 'Deluxe', category: 'KITCHENWARE', orders: [ { customer_id: '[email protected]', orderdate: ISODate('2020-01-01T08:25:37.000Z'), value: 63.13 } ] }
컬렉션을 연결하고 필드를 가져오는 조회 단계를 추가합니다.
파이프라인 의 첫 번째 단계는 단계로,$lookup
각 orders
컬렉션 의 products
두 필드를 기준으로 컬렉션 컬렉션 에 조인합니다. 조회 단계에는 조인을 구성하기 위한 파이프라인 포함되어 있습니다.
포함된 파이프라인 만든 다음 단계를 추가하여 조인 $match
양쪽에 있는 두 필드의 값을 일치시킵니다. 다음 코드에서는 name
variation
$lookup 단계를 만들때 설정하다 및 필드에 별칭을 사용합니다.
bson_t embedded_pipeline; bson_array_builder_t *bab = bson_array_builder_new(); bson_array_builder_append_document(bab, BCON_NEW( "$match", "{", "$expr", "{", "$and", "[", "{", "$eq", "[", BCON_UTF8("$product_name"), BCON_UTF8("$$prdname"), "]", "}", "{", "$eq", "[", BCON_UTF8("$product_variation"), BCON_UTF8("$$prdvartn"), "]", "}", "]", "}", "}"));
내장된 파이프라인 내에서 에 접수된 주문과 $match
2020 일치하도록 다른 단계를 추가합니다.
bson_array_builder_append_document(bab, BCON_NEW( "$match", "{", "orderdate", "{", "$gte", BCON_DATE_TIME(1577836800000UL), "$lt", BCON_DATE_TIME(1609459200000UL), "}", "}"));
포함된 파이프라인 내에서 단계를 추가하여 조인의 컬렉션 사이드에서 $unset
불필요한 필드를 제거 orders
.
bson_array_builder_append_document(bab, BCON_NEW( "$unset", "[", BCON_UTF8("_id"), BCON_UTF8("product_name"), BCON_UTF8("product_variation"), "]")); // Builds the embedded pipeline array and cleans up resources bson_array_builder_build(bab, &embedded_pipeline); bson_array_builder_destroy(bab);
임베디드 파이프라인이 완료되면 $lookup
단계를 기본 집계 파이프라인에 추가합니다. 처리된 조회 필드를 orders
배열 필드에 저장하도록 이 단계를 구성합니다.
"{", "$lookup", "{", "from", BCON_UTF8("orders"), "let", "{", "prdname", BCON_UTF8("$name"), "prdvartn", BCON_UTF8("$variation"), "}", "pipeline", BCON_ARRAY(&embedded_pipeline), "as", BCON_UTF8("orders"), "}", "}",
2020에서 주문한 제품에 대해 일치 단계를 추가합니다.
다음으로, 이전 단계에서 계산된 배열 기반으로 단계를 추가하여 에 주문이 하나 이상 있는 $match
제품만 2020 표시합니다.orders
"{", "$match", "{", "orders", "{", "$ne", "[", "]", "}", "}", "}",
불필요한 필드를 제거 하려면 설정되지 않은 단계를 추가합니다.
마지막으로 단계를 $unset
추가합니다.$unset
단계는 _id
description
결과 문서에서 및 필드를 제거합니다.
"{", "$unset", "[", BCON_UTF8("_id"), BCON_UTF8("description"), "]", "}",
집계 파이프라인 실행합니다.
products
collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.
mongoc_cursor_t *results = mongoc_collection_aggregate(products, MONGOC_QUERY_NONE, pipeline, NULL, NULL); bson_destroy(&embedded_pipeline); bson_destroy(pipeline);
정리 문에 다음 줄을 추가하여 컬렉션 리소스를 정리해야 합니다.
mongoc_collection_destroy(products); mongoc_collection_destroy(orders);
마지막으로 셸 에서 다음 명령을 실행 실행 파일을 생성하고 실행 .
gcc -o aggc agg-tutorial.c $(pkg-config --libs --cflags libmongoc-1.0) ./aggc
팁
한 번의 호출에서 앞의 명령을 실행 데 연결 오류가 발생하는 경우 별도로 실행 수 있습니다.
집계 결과를 해석합니다.
애그리게이션된 결과에는 두 개의 문서가 포함됩니다. 이 문서는 2020년에 주문이 접수된 제품을 나타냅니다. 각 문서에는 해당 제품의 각 주문에 대한 세부 정보를 나열하는 orders
배열 필드가 포함되어 있습니다.
{ "name" : "Asus Laptop", "variation" : "Standard Display", "category" : "ELECTRONICS", "orders" : [ { "customer_id" : "[email protected]", "orderdate" : { "$date" : { "$numberLong" : "1590822952000" } }, "value" : { "$numberDouble" : "431.43000000000000682" } }, { "customer_id" : "[email protected]", "orderdate" : { "$date" : { "$numberLong" : "1608976546000" } }, "value" : { "$numberDouble" : "429.64999999999997726" } } ] } { "name" : "Morphy Richards Food Mixer", "variation" : "Deluxe", "category" : "KITCHENWARE", "orders" : [ { "customer_id" : "[email protected]", "orderdate" : { "$date" : { "$numberLong" : "1577869537000" } }, "value" : { "$numberDouble" : "63.130000000000002558" } } ] }
결과 문서에는 orders
collection 및 products
collection에 있는 문서의 세부 정보가 제품 이름 및 변형으로 결합되어 포함됩니다.
컬렉션을 연결하고 필드를 가져오는 조회 단계를 추가합니다.
파이프라인 의 첫 번째 단계는 단계로,$lookup
각 orders
컬렉션 의 products
두 필드를 기준으로 컬렉션 컬렉션 에 조인합니다. 조회 단계에는 조인을 구성하기 위한 파이프라인 포함되어 있습니다.
포함된 파이프라인 내에서 단계를 추가하여 조인 $match
양쪽에 있는 두 필드의 값을 일치시킵니다. 다음 코드에서는 name
variation
$lookup 단계를 만들때 설정하다 및 필드에 별칭을 사용합니다.
auto embed_match_stage1 = bsoncxx::from_json(R"({ "$match": { "$expr": { "$and": [ { "$eq": ["$product_name", "$$prdname"] }, { "$eq": ["$product_variation", "$$prdvartn"] } ] } } })");
내장된 파이프라인 내에서 에 접수된 주문과 $match
2020 일치하도록 다른 단계를 추가합니다.
auto embed_match_stage2 = bsoncxx::from_json(R"({ "$match": { "orderdate": { "$gte": { "$date": 1577836800000 }, "$lt": { "$date": 1609459200000 } } } })");
포함된 파이프라인 내에서 단계를 추가하여 조인의 컬렉션 사이드에서 $unset
불필요한 필드를 제거 orders
.
auto embed_unset_stage = bsoncxx::from_json(R"({ "$unset": ["_id", "product_name", "product_variation"] })");
임베디드 파이프라인이 완료되면 $lookup
단계를 기본 집계 파이프라인에 추가합니다. 처리된 조회 필드를 orders
배열 필드에 저장하도록 이 단계를 구성합니다.
pipeline.lookup(make_document( kvp("from", "orders"), kvp("let", make_document( kvp("prdname", "$name"), kvp("prdvartn", "$variation") )), kvp("pipeline", make_array(embed_match_stage1, embed_match_stage2, embed_unset_stage)), kvp("as", "orders") ));
2020에서 주문한 제품에 대해 일치 단계를 추가합니다.
다음으로, 이전 단계에서 계산된 배열 기반으로 단계를 추가하여 에 주문이 하나 이상 있는 $match
제품만 2020 표시합니다.orders
pipeline.match(bsoncxx::from_json(R"({ "orders": { "$ne": [] } })"));
불필요한 필드를 제거 하려면 설정되지 않은 단계를 추가합니다.
마지막으로 단계를 $unset
추가합니다.$unset
단계는 _id
description
결과 문서에서 및 필드를 제거합니다.
pipeline.append_stage(bsoncxx::from_json(R"({ "$unset": ["_id", "description"] })"));
집계 결과를 해석합니다.
애그리게이션된 결과에는 두 개의 문서가 포함됩니다. 이 문서는 2020년에 주문이 접수된 제품을 나타냅니다. 각 문서에는 해당 제품의 각 주문에 대한 세부 정보를 나열하는 orders
배열 필드가 포함되어 있습니다.
{ "name" : "Asus Laptop", "variation" : "Standard Display", "category" : "ELECTRONICS", "orders" : [ { "customer_id" : "[email protected]", "orderdate" : { "$date" : "2020-05-30T06:55:52Z" }, "value" : 431.43000000000000682 }, { "customer_id" : "[email protected]", "orderdate" : { "$date" : "2020-12-26T08:55:46Z" }, "value" : 429.64999999999997726 } ] } { "name" : "Morphy Richards Food Mixer", "variation" : "Deluxe", "category" : "KITCHENWARE", "orders" : [ { "customer_id" : "[email protected]", "orderdate" : { "$date" : "2020-01-01T06:45:37Z" }, "value" : 63.130000000000002558 } ] }
결과 문서에는 orders
collection 및 products
collection에 있는 문서의 세부 정보가 제품 이름 및 변형으로 결합되어 포함됩니다.
컬렉션을 연결하고 필드를 가져오는 조회 단계를 추가합니다.
파이프라인 의 첫 번째 단계는 단계로,$lookup
각 orders
컬렉션 의 products
두 필드를 기준으로 컬렉션 컬렉션 에 조인합니다. 조회 단계에는 조인을 구성하기 위한 파이프라인 포함되어 있습니다.
포함된 파이프라인 $match
인스턴스화한 다음 단계를 연결하여 조인 양쪽에 있는 두 필드의 값을 일치시킵니다. 다음 코드에서는 Name
Variation
$lookup 단계를 만들때 설정하다 및 필드에 별칭을 사용합니다.
var embeddedPipeline = new EmptyPipelineDefinition<Order>() .Match(new BsonDocument("$expr", new BsonDocument("$and", new BsonArray { new BsonDocument("$eq", new BsonArray { "$ProductName", "$$prdname" }), new BsonDocument("$eq", new BsonArray { "$ProductVariation", "$$prdvartn" }) })))
내장된 파이프라인 내에서 에 접수된 주문과 $match
2020 일치하도록 다른 단계를 추가합니다.
.Match(o => o.OrderDate >= DateTime.Parse("2020-01-01T00:00:00Z") && o.OrderDate < DateTime.Parse("2021-01-01T00:00:00Z"))
포함된 파이프라인 내에서 단계를 추가하여 조인의 컬렉션 사이드에서 $project
불필요한 필드를 제거 orders
.
.Project(Builders<Order>.Projection .Exclude(o => o.Id) .Exclude(o => o.ProductName) .Exclude(o => o.ProductVariation));
임베디드 파이프라인 완료되면 products
컬렉션 에서 메인 집계 시작하고 $lookup
단계를 연결합니다. 처리된 조회 필드를 Orders
배열 필드 에 저장 하도록 이 단계를 구성합니다.
var results = products.Aggregate() .Lookup<Order, BsonDocument, IEnumerable<BsonDocument>, BsonDocument>( foreignCollection: orders, let: new BsonDocument { { "prdname", "$Name" }, { "prdvartn", "$Variation" } }, lookupPipeline: embeddedPipeline, "Orders" )
2020에서 주문한 제품에 대해 일치 단계를 추가합니다.
다음으로, 이전 단계에서 만든 배열 기반으로 단계를 추가하여 에 주문이 하나 이상 있는 제품만 $match
2020 표시합니다.Orders
.Match(Builders<BsonDocument>.Filter.Ne("Orders", new BsonArray()))
불필요한 필드를 제거 위해 프로젝션 단계를 추가합니다.
마지막으로 단계를 $project
추가합니다.$project
단계는 _id
Description
결과 문서에서 및 필드를 제거합니다.
.Project(Builders<BsonDocument>.Projection .Exclude("_id") .Exclude("Description") );
집계 실행하고 결과를 해석합니다.
마지막으로 IDE에서 애플리케이션 실행 하고 결과를 검사합니다.
애그리게이션된 결과에는 두 개의 문서가 포함됩니다. 이 문서는 2020년에 주문이 접수된 제품을 나타냅니다. 각 문서에는 해당 제품의 각 주문에 대한 세부 정보를 나열하는 Orders
배열 필드가 포함되어 있습니다.
{ "Name" : "Asus Laptop", "Variation" : "Standard Display", "Category" : "ELECTRONICS", "Orders" : [{ "CustomerId" : "[email protected]", "OrderDate" : { "$date" : "2020-05-30T08:35:52Z" }, "Value" : 431.43000000000001 }, { "CustomerId" : "[email protected]", "OrderDate" : { "$date" : "2020-12-26T08:55:46Z" }, "Value" : 429.64999999999998 }] } { "Name" : "Morphy Richards Food Mixer", "Variation" : "Deluxe", "Category" : "KITCHENWARE", "Orders" : [{ "CustomerId" : "[email protected]", "OrderDate" : { "$date" : "2020-01-01T08:25:37Z" }, "Value" : 63.130000000000003 }] }
결과 문서에는 orders
collection 및 products
collection에 있는 문서의 세부 정보가 제품 이름 및 변형으로 결합되어 포함됩니다.
컬렉션을 연결하고 필드를 가져오는 조회 단계를 추가합니다.
파이프라인 의 첫 번째 단계는 단계로,$lookup
각 orders
컬렉션 의 products
두 필드를 기준으로 컬렉션 컬렉션 에 조인합니다. 조회 단계에는 조인을 구성하기 위한 파이프라인 포함되어 있습니다.
포함된 파이프라인 내에서 단계를 추가하여 조인 $match
양쪽에 있는 두 필드의 값을 일치시킵니다. 다음 코드에서는 name
variation
$lookup 단계를 만들때 설정하다 및 필드에 별칭을 사용합니다.
embeddedMatchStage1 := bson.D{ {Key: "$match", Value: bson.D{ {Key: "$expr", Value: bson.D{ {Key: "$and", Value: bson.A{ bson.D{{Key: "$eq", Value: bson.A{"$product_name", "$$prdname"}}}, bson.D{{Key: "$eq", Value: bson.A{"$product_variation", "$$prdvartn"}}}, }}, }}, }}, }
내장된 파이프라인 내에서 에 접수된 주문과 $match
2020 일치하도록 다른 단계를 추가합니다.
embeddedMatchStage2 := bson.D{ {Key: "$match", Value: bson.D{ {Key: "orderdate", Value: bson.D{ {Key: "$gte", Value: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)}, {Key: "$lt", Value: time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)}, }}, }}, }
포함된 파이프라인 내에서 단계를 추가하여 조인의 컬렉션 사이드에서 $unset
불필요한 필드를 제거 orders
.
embeddedUnsetStage := bson.D{ {Key: "$unset", Value: bson.A{"_id", "product_name", "product_variation"}}, }
임베디드 파이프라인이 완료되면 $lookup
단계를 기본 집계 파이프라인에 추가합니다. 처리된 조회 필드를 orders
배열 필드에 저장하도록 이 단계를 구성합니다.
embeddedPipeline := mongo.Pipeline{embeddedMatchStage1, embeddedMatchStage2, embeddedUnsetStage} lookupStage := bson.D{ {Key: "$lookup", Value: bson.D{ {Key: "from", Value: "orders"}, {Key: "let", Value: bson.D{ {Key: "prdname", Value: "$name"}, {Key: "prdvartn", Value: "$variation"}, }}, {Key: "pipeline", Value: embeddedPipeline}, {Key: "as", Value: "orders"}, }}, }
2020에서 주문한 제품에 대해 일치 단계를 추가합니다.
다음으로, 이전 단계에서 계산된 배열 기반으로 단계를 추가하여 에 주문이 하나 이상 있는 $match
제품만 2020 표시합니다.orders
matchStage := bson.D{ {Key: "$match", Value: bson.D{ {Key: "orders", Value: bson.D{{Key: "$ne", Value: bson.A{}}}}, }}, }
불필요한 필드를 제거 하려면 설정되지 않은 단계를 추가합니다.
마지막으로 단계를 $unset
추가합니다.$unset
단계는 _id
description
결과 문서에서 및 필드를 제거합니다.
unsetStage := bson.D{ {Key: "$unset", Value: bson.A{"_id", "description"}}, }
집계 결과를 해석합니다.
애그리게이션된 결과에는 두 개의 문서가 포함됩니다. 이 문서는 2020년에 주문이 접수된 제품을 나타냅니다. 각 문서에는 해당 제품의 각 주문에 대한 세부 정보를 나열하는 orders
배열 필드가 포함되어 있습니다.
{"name":"Asus Laptop","variation":"Standard Display","category":"ELECTRONICS","orders":[{"customer_id":"[email protected]","orderdate":{"$date":"2020-05-30T08:35:52Z"},"value":431.42999267578125},{"customer_id":"[email protected]","orderdate":{"$date":"2020-12-26T08:55:46Z"},"value":429.6499938964844}]} {"name":"Morphy Richards Food Mixer","variation":"Deluxe","category":"KITCHENWARE","orders":[{"customer_id":"[email protected]","orderdate":{"$date":"2020-01-01T08:25:37Z"},"value":63.130001068115234}]}
결과 문서에는 orders
collection 및 products
collection에 있는 문서의 세부 정보가 제품 이름 및 변형으로 결합되어 포함됩니다.
컬렉션을 연결하고 필드를 가져오는 조회 단계를 추가합니다.
파이프라인 의 첫 번째 단계는 단계로,$lookup
각 orders
컬렉션 의 products
두 필드를 기준으로 컬렉션 컬렉션 에 조인합니다. 조회 단계에는 조인을 구성하기 위한 파이프라인 포함되어 있습니다.
포함된 파이프라인 내에서 단계를 추가하여 조인 $match
양쪽에 있는 두 필드의 값을 일치시킵니다. 다음 코드에서는 name
variation
$lookup 단계를 만들때 설정하다 및 필드에 별칭을 사용합니다.
List<Bson> embeddedPipeline = new ArrayList<>(); embeddedPipeline.add(Aggregates.match( Filters.expr( Filters.and( new Document("$eq", Arrays.asList("$product_name", "$$prdname")), new Document("$eq", Arrays.asList("$product_variation", "$$prdvartn")) ) ) ));
내장된 파이프라인 내에서 에 접수된 주문과 $match
2020 일치하도록 다른 단계를 추가합니다.
embeddedPipeline.add(Aggregates.match(Filters.and( Filters.gte("orderdate", LocalDateTime.parse("2020-01-01T00:00:00")), Filters.lt("orderdate", LocalDateTime.parse("2021-01-01T00:00:00")) )));
포함된 파이프라인 내에서 단계를 추가하여 조인의 컬렉션 사이드에서 $unset
불필요한 필드를 제거 orders
.
embeddedPipeline.add(Aggregates.unset("_id", "product_name", "product_variation"));
임베디드 파이프라인이 완료되면 $lookup
단계를 기본 집계 파이프라인에 추가합니다. 처리된 조회 필드를 orders
배열 필드에 저장하도록 이 단계를 구성합니다.
pipeline.add(Aggregates.lookup( "orders", Arrays.asList( new Variable<>("prdname", "$name"), new Variable<>("prdvartn", "$variation") ), embeddedPipeline, "orders" ));
2020에서 주문한 제품에 대해 일치 단계를 추가합니다.
다음으로, 이전 단계에서 계산된 배열 기반으로 단계를 추가하여 에 주문이 하나 이상 있는 $match
제품만 2020 표시합니다.orders
pipeline.add(Aggregates.match( Filters.ne("orders", new ArrayList<>()) ));
불필요한 필드를 제거 하려면 설정되지 않은 단계를 추가합니다.
마지막으로 단계를 $unset
추가합니다.$unset
단계는 _id
description
결과 문서에서 및 필드를 제거합니다.
pipeline.add(Aggregates.unset("_id", "description"));
집계 결과를 해석합니다.
애그리게이션된 결과에는 두 개의 문서가 포함됩니다. 이 문서는 2020년에 주문이 접수된 제품을 나타냅니다. 각 문서에는 해당 제품의 각 주문에 대한 세부 정보를 나열하는 orders
배열 필드가 포함되어 있습니다.
{"name": "Asus Laptop", "variation": "Standard Display", "category": "ELECTRONICS", "orders": [{"customer_id": "[email protected]", "orderdate": {"$date": "2020-05-30T08:35:52Z"}, "value": 431.43}, {"customer_id": "[email protected]", "orderdate": {"$date": "2020-12-26T08:55:46Z"}, "value": 429.65}]} {"name": "Morphy Richards Food Mixer", "variation": "Deluxe", "category": "KITCHENWARE", "orders": [{"customer_id": "[email protected]", "orderdate": {"$date": "2020-01-01T08:25:37Z"}, "value": 63.13}]}
결과 문서에는 orders
collection 및 products
collection에 있는 문서의 세부 정보가 제품 이름 및 변형으로 결합되어 포함됩니다.
컬렉션을 연결하고 필드를 가져오는 조회 단계를 추가합니다.
파이프라인 의 첫 번째 단계는 단계로,$lookup
각 orders
컬렉션 의 products
두 필드를 기준으로 컬렉션 컬렉션 에 조인합니다. 조회 단계에는 조인을 구성하기 위한 파이프라인 포함되어 있습니다.
포함된 파이프라인 내에서 단계를 추가하여 조인 $match
양쪽에 있는 두 필드의 값을 일치시킵니다. 다음 코드에서는 name
variation
$lookup 단계를 만들때 설정하다 및 필드에 별칭을 사용합니다.
val embeddedPipeline = mutableListOf<Bson>() embeddedPipeline.add( Aggregates.match( Filters.expr( Document( "\$and", listOf( Document("\$eq", listOf("\$${Order::productName.name}", "$\$prdname")), Document("\$eq", listOf("\$${Order::productVariation.name}", "$\$prdvartn")) ) ) ) ) )
내장된 파이프라인 내에서 에 접수된 주문과 $match
2020 일치하도록 다른 단계를 추가합니다.
embeddedPipeline.add( Aggregates.match( Filters.and( Filters.gte( Order::orderDate.name, LocalDateTime.parse("2020-01-01T00:00:00").toJavaLocalDateTime() ), Filters.lt(Order::orderDate.name, LocalDateTime.parse("2021-01-01T00:00:00").toJavaLocalDateTime()) ) ) )
포함된 파이프라인 내에서 단계를 추가하여 조인의 컬렉션 사이드에서 $unset
불필요한 필드를 제거 orders
.
embeddedPipeline.add(Aggregates.unset("_id", Order::productName.name, Order::productVariation.name))
임베디드 파이프라인이 완료되면 $lookup
단계를 기본 집계 파이프라인에 추가합니다. 처리된 조회 필드를 orders
배열 필드에 저장하도록 이 단계를 구성합니다.
pipeline.add( Aggregates.lookup( "orders", listOf( Variable("prdname", "\$${Product::name.name}"), Variable("prdvartn", "\$${Product::variation.name}") ), embeddedPipeline, "orders" ) )
2020에서 주문한 제품에 대해 일치 단계를 추가합니다.
다음으로, 이전 단계에서 계산된 배열 기반으로 단계를 추가하여 에 주문이 하나 이상 있는 $match
제품만 2020 표시합니다.orders
pipeline.add( Aggregates.match( Filters.ne("orders", mutableListOf<Document>()) ) )
불필요한 필드를 제거 하려면 설정되지 않은 단계를 추가합니다.
마지막으로 단계를 $unset
추가합니다.$unset
단계는 _id
description
결과 문서에서 및 필드를 제거합니다.
pipeline.add(Aggregates.unset("_id", "description"))
집계 결과를 해석합니다.
애그리게이션된 결과에는 두 개의 문서가 포함됩니다. 이 문서는 2020년에 주문이 접수된 제품을 나타냅니다. 각 문서에는 해당 제품의 각 주문에 대한 세부 정보를 나열하는 orders
배열 필드가 포함되어 있습니다.
Document{{name=Asus Laptop, variation=Standard Display, category=ELECTRONICS, orders=[Document{{[email protected], orderDate=Sat May 30 04:35:52 EDT 2020, value=431.43}}, Document{{[email protected], orderDate=Sat Dec 26 03:55:46 EST 2020, value=429.65}}]}} Document{{name=Morphy Richards Food Mixer, variation=Deluxe, category=KITCHENWARE, orders=[Document{{[email protected], orderDate=Wed Jan 01 03:25:37 EST 2020, value=63.13}}]}}
결과 문서에는 orders
collection 및 products
collection에 있는 문서의 세부 정보가 제품 이름 및 변형으로 결합되어 포함됩니다.
컬렉션을 연결하고 필드를 가져오는 조회 단계를 추가합니다.
파이프라인 의 첫 번째 단계는 단계로,$lookup
각 orders
컬렉션 의 products
두 필드를 기준으로 컬렉션 컬렉션 에 조인합니다. 조회 단계에는 조인을 구성하기 위한 파이프라인 포함되어 있습니다.
포함된 파이프라인 내에서 단계를 추가하여 조인 $match
양쪽에 있는 두 필드의 값을 일치시킵니다. 다음 코드에서는 name
variation
$lookup 단계를 만들때 설정하다 및 필드에 별칭을 사용합니다.
const embedded_pl = []; embedded_pl.push({ $match: { $expr: { $and: [ { $eq: ["$product_name", "$$prdname"] }, { $eq: ["$product_variation", "$$prdvartn"] }, ], }, }, });
내장된 파이프라인 내에서 에 접수된 주문과 $match
2020 일치하도록 다른 단계를 추가합니다.
embedded_pl.push({ $match: { orderdate: { $gte: new Date("2020-01-01T00:00:00Z"), $lt: new Date("2021-01-01T00:00:00Z"), }, }, });
포함된 파이프라인 내에서 단계를 추가하여 조인의 컬렉션 사이드에서 $unset
불필요한 필드를 제거 orders
.
embedded_pl.push({ $unset: ["_id", "product_name", "product_variation"], });
임베디드 파이프라인이 완료되면 $lookup
단계를 기본 집계 파이프라인에 추가합니다. 처리된 조회 필드를 orders
배열 필드에 저장하도록 이 단계를 구성합니다.
pipeline.push({ $lookup: { from: "orders", let: { prdname: "$name", prdvartn: "$variation", }, pipeline: embedded_pl, as: "orders", }, });
2020에서 주문한 제품에 대해 일치 단계를 추가합니다.
다음으로, 이전 단계에서 계산된 배열 기반으로 단계를 추가하여 에 주문이 하나 이상 있는 $match
제품만 2020 표시합니다.orders
pipeline.push({ $match: { orders: { $ne: [] }, }, });
불필요한 필드를 제거 하려면 설정되지 않은 단계를 추가합니다.
마지막으로 단계를 $unset
추가합니다.$unset
단계는 _id
description
결과 문서에서 및 필드를 제거합니다.
pipeline.push({ $unset: ["_id", "description"], });
집계 결과를 해석합니다.
애그리게이션된 결과에는 두 개의 문서가 포함됩니다. 이 문서는 2020년에 주문이 접수된 제품을 나타냅니다. 각 문서에는 해당 제품의 각 주문에 대한 세부 정보를 나열하는 orders
배열 필드가 포함되어 있습니다.
{ name: 'Asus Laptop', variation: 'Standard Display', category: 'ELECTRONICS', orders: [ { customer_id: '[email protected]', orderdate: 2020-05-30T08:35:52.000Z, value: 431.43 }, { customer_id: '[email protected]', orderdate: 2020-12-26T08:55:46.000Z, value: 429.65 } ] } { name: 'Morphy Richards Food Mixer', variation: 'Deluxe', category: 'KITCHENWARE', orders: [ { customer_id: '[email protected]', orderdate: 2020-01-01T08:25:37.000Z, value: 63.13 } ] }
결과 문서에는 orders
collection 및 products
collection에 있는 문서의 세부 정보가 제품 이름 및 변형으로 결합되어 포함됩니다.
컬렉션을 연결하고 필드를 가져오는 조회 단계를 추가합니다.
파이프라인 의 첫 번째 $lookup
단계는 orders
products
단계로, 각 컬렉션 의 두 필드를 기준으로 컬렉션 컬렉션 에 조인합니다. 조회 단계에는 조인을 구성하기 위한 파이프라인 포함되어 있습니다. 먼저 임베디드 파이프라인 생성합니다.
$embeddedPipeline = new Pipeline( // Add stages within embedded pipeline. };
포함된 파이프라인 내에서 단계를 추가하여 조인 $match
양쪽에 있는 두 필드의 값을 일치시킵니다. 다음 코드에서는 name
variation
$lookup 단계를 만들때 설정하다 및 필드에 별칭을 사용합니다.
Stage::match( Query::expr( Expression::and( Expression::eq( Expression::stringFieldPath('product_name'), Expression::variable('prdname') ), Expression::eq( Expression::stringFieldPath('product_variation'), Expression::variable('prdvartn') ), ) ) ),
내장된 파이프라인 내에서 에 접수된 주문과 $match
2020 일치하도록 다른 단계를 추가합니다.
Stage::match( orderdate: [ Query::gte(new UTCDateTime(new DateTimeImmutable('2020-01-01T00:00:00'))), Query::lt(new UTCDateTime(new DateTimeImmutable('2021-01-01T00:00:00'))), ] ),
포함된 파이프라인 내에서 단계를 추가하여 조인의 컬렉션 사이드에서 $unset
불필요한 필드를 제거 orders
.
Stage::unset('_id', 'product_name', 'product_variation')
다음으로 Pipeline
인스턴스 외부에서 팩토리 함수에 $lookup
단계를 만듭니다. 처리된 조회 필드를 orders
배열 필드 에 저장 하도록 이 단계를 구성합니다.
function lookupOrdersStage(Pipeline $embeddedPipeline) { return Stage::lookup( from: 'orders', let: object( prdname: Expression::stringFieldPath('name'), prdvartn: Expression::stringFieldPath('variation'), ), pipeline: $embeddedPipeline, as: 'orders', ); }
그런 다음 메인 Pipeline
인스턴스 에서 lookupOrdersStage()
함수를 호출합니다.
lookupOrdersStage($embeddedPipeline),
2020에서 주문한 제품에 대해 일치 단계를 추가합니다.
다음으로, 이전 단계에서 계산된 배열 기반으로 단계를 추가하여 에 주문이 하나 이상 있는 $match
제품만 2020 표시합니다.orders
Stage::match( orders: Query::ne([]) ),
불필요한 필드를 제거 하려면 설정되지 않은 단계를 추가합니다.
마지막으로 단계를 $unset
추가합니다.$unset
단계는 _id
description
결과 문서에서 및 필드를 제거합니다.
Stage::unset('_id', 'description')
집계 결과를 해석합니다.
애그리게이션된 결과에는 두 개의 문서가 포함됩니다. 이 문서는 2020년에 주문이 접수된 제품을 나타냅니다. 각 문서에는 해당 제품의 각 주문에 대한 세부 정보를 나열하는 orders
배열 필드가 포함되어 있습니다.
{ "name": "Asus Laptop", "variation": "Standard Display", "category": "ELECTRONICS", "orders": [ { "customer_id": "[email protected]", "orderdate": { "$date": { "$numberLong": "1590827752000" } }, "value": 431.43 }, { "customer_id": "[email protected]", "orderdate": { "$date": { "$numberLong": "1608972946000" } }, "value": 429.65 } ] } { "name": "Morphy Richards Food Mixer", "variation": "Deluxe", "category": "KITCHENWARE", "orders": [ { "customer_id": "[email protected]", "orderdate": { "$date": { "$numberLong": "1577867137000" } }, "value": 63.13 } ] }
결과 문서에는 orders
collection 및 products
collection에 있는 문서의 세부 정보가 제품 이름 및 변형으로 결합되어 포함됩니다.
컬렉션을 연결하고 필드를 가져오는 조회 단계를 추가합니다.
파이프라인 의 첫 번째 단계는 단계로,$lookup
각 orders
컬렉션 의 products
두 필드를 기준으로 컬렉션 컬렉션 에 조인합니다. 조회 단계에는 조인을 구성하기 위한 파이프라인 포함되어 있습니다.
포함된 파이프라인 내에서 단계를 추가하여 조인 $match
양쪽에 있는 두 필드의 값을 일치시킵니다. 다음 코드에서는 name
variation
$lookup 단계를 만들때 설정하다 및 필드에 별칭을 사용합니다.
embedded_pl = [ { "$match": { "$expr": { "$and": [ {"$eq": ["$product_name", "$$prdname"]}, {"$eq": ["$product_variation", "$$prdvartn"]}, ] } } } ]
내장된 파이프라인 내에서 에 접수된 주문과 $match
2020 일치하도록 다른 단계를 추가합니다.
embedded_pl.append( { "$match": { "orderdate": { "$gte": datetime(2020, 1, 1, 0, 0, 0), "$lt": datetime(2021, 1, 1, 0, 0, 0), } } } )
포함된 파이프라인 내에서 단계를 추가하여 조인의 컬렉션 사이드에서 $unset
불필요한 필드를 제거 orders
.
embedded_pl.append({"$unset": ["_id", "product_name", "product_variation"]})
임베디드 파이프라인이 완료되면 $lookup
단계를 기본 집계 파이프라인에 추가합니다. 처리된 조회 필드를 orders
배열 필드에 저장하도록 이 단계를 구성합니다.
pipeline.append( { "$lookup": { "from": "orders", "let": {"prdname": "$name", "prdvartn": "$variation"}, "pipeline": embedded_pl, "as": "orders", } } )
2020에서 주문한 제품에 대해 일치 단계를 추가합니다.
다음으로, 이전 단계에서 계산된 배열 기반으로 단계를 추가하여 에 주문이 하나 이상 있는 $match
제품만 2020 표시합니다.orders
pipeline.append({"$match": {"orders": {"$ne": []}}})
불필요한 필드를 제거 하려면 설정되지 않은 단계를 추가합니다.
마지막으로 단계를 $unset
추가합니다.$unset
단계는 _id
description
결과 문서에서 및 필드를 제거합니다.
pipeline.append({"$unset": ["_id", "description"]})
집계 결과를 해석합니다.
애그리게이션된 결과에는 두 개의 문서가 포함됩니다. 이 문서는 2020년에 주문이 접수된 제품을 나타냅니다. 각 문서에는 해당 제품의 각 주문에 대한 세부 정보를 나열하는 orders
배열 필드가 포함되어 있습니다.
{'name': 'Asus Laptop', 'variation': 'Standard Display', 'category': 'ELECTRONICS', 'orders': [{'customer_id': '[email protected]', 'orderdate': datetime.datetime(2020, 5, 30, 8, 35, 52), 'value': 431.43}, {'customer_id': '[email protected]', 'orderdate': datetime.datetime(2020, 12, 26, 8, 55, 46), 'value': 429.65}]} {'name': 'Morphy Richards Food Mixer', 'variation': 'Deluxe', 'category': 'KITCHENWARE', 'orders': [{'customer_id': '[email protected]', 'orderdate': datetime.datetime(2020, 1, 1, 8, 25, 37), 'value': 63.13}]}
결과 문서에는 orders
collection 및 products
collection에 있는 문서의 세부 정보가 제품 이름 및 변형으로 결합되어 포함됩니다.
컬렉션을 연결하고 필드를 가져오는 조회 단계를 추가합니다.
파이프라인 의 첫 번째 단계는 단계로,$lookup
각 orders
컬렉션 의 products
두 필드를 기준으로 컬렉션 컬렉션 에 조인합니다. 조회 단계에는 조인을 구성하기 위한 파이프라인 포함되어 있습니다.
포함된 파이프라인 내에서 단계를 추가하여 조인 $match
양쪽에 있는 두 필드의 값을 일치시킵니다. 다음 코드에서는 name
variation
$lookup 단계를 만들때 설정하다 및 필드에 별칭을 사용합니다.
{ "$match": { "$expr": { "$and": [ { "$eq": ["$product_name", "$$prdname"] }, { "$eq": ["$product_variation", "$$prdvartn"] }, ], }, }, },
내장된 파이프라인 내에서 에 접수된 주문과 $match
2020 일치하도록 다른 단계를 추가합니다.
{ "$match": { orderdate: { "$gte": DateTime.parse("2020-01-01T00:00:00Z"), "$lt": DateTime.parse("2021-01-01T00:00:00Z"), }, }, },
포함된 파이프라인 내에서 단계를 추가하여 조인의 컬렉션 사이드에서 $unset
불필요한 필드를 제거 orders
.
{ "$unset": ["_id", "product_name", "product_variation"], },
임베디드 파이프라인이 완료되면 $lookup
단계를 기본 집계 파이프라인에 추가합니다. 처리된 조회 필드를 orders
배열 필드에 저장하도록 이 단계를 구성합니다.
{ "$lookup": { from: "orders", let: { prdname: "$name", prdvartn: "$variation", }, pipeline: embedded_pipeline, as: "orders", }, },
2020에서 주문한 제품에 대해 일치 단계를 추가합니다.
다음으로, 이전 단계에서 계산된 배열 기반으로 단계를 추가하여 에 주문이 하나 이상 있는 $match
제품만 2020 표시합니다.orders
{ "$match": { orders: { "$ne": [] }, }, },
불필요한 필드를 제거 하려면 설정되지 않은 단계를 추가합니다.
마지막으로 단계를 $unset
추가합니다.$unset
단계는 _id
description
결과 문서에서 및 필드를 제거합니다.
{ "$unset": ["_id", "description"], },
집계 결과를 해석합니다.
애그리게이션된 결과에는 두 개의 문서가 포함됩니다. 이 문서는 2020년에 주문이 접수된 제품을 나타냅니다. 각 문서에는 해당 제품의 각 주문에 대한 세부 정보를 나열하는 orders
배열 필드가 포함되어 있습니다.
{"name"=>"Asus Laptop", "variation"=>"Standard Display", "category"=>"ELECTRONICS", "orders"=>[{"customer_id"=>"[email protected]", "orderdate"=>2020-05-30 08:35:52 UTC, "value"=>431.43}, {"customer_id"=>"[email protected]", "orderdate"=>2020-12-26 08:55:46 UTC, "value"=>429.65}]} {"name"=>"Morphy Richards Food Mixer", "variation"=>"Deluxe", "category"=>"KITCHENWARE", "orders"=>[{"customer_id"=>"[email protected]", "orderdate"=>2020-01-01 08:25:37 UTC, "value"=>63.13}]}
결과 문서에는 orders
collection 및 products
collection에 있는 문서의 세부 정보가 제품 이름 및 변형으로 결합되어 포함됩니다.
컬렉션을 연결하고 필드를 가져오는 조회 단계를 추가합니다.
파이프라인 의 첫 번째 단계는 단계로,$lookup
각 orders
컬렉션 의 products
두 필드를 기준으로 컬렉션 컬렉션 에 조인합니다. 조회 단계에는 조인을 구성하기 위한 파이프라인 포함되어 있습니다.
포함된 파이프라인 내에서 단계를 추가하여 조인 $match
양쪽에 있는 두 필드의 값을 일치시킵니다. 다음 코드에서는 name
variation
$lookup 단계를 만들때 설정하다 및 필드에 별칭을 사용합니다.
let mut embedded_pipeline = Vec::new(); embedded_pipeline.push(doc! { "$match": { "$expr": { "$and": [ { "$eq": ["$product_name", "$$prdname"] }, { "$eq": ["$product_variation", "$$prdvartn"] } ] } } });
내장된 파이프라인 내에서 에 접수된 주문과 $match
2020 일치하도록 다른 단계를 추가합니다.
embedded_pipeline.push(doc! { "$match": { "order_date": { "$gte": DateTime::builder().year(2020).month(1).day(1).build().unwrap(), "$lt": DateTime::builder().year(2021).month(1).day(1).build().unwrap() } } });
포함된 파이프라인 내에서 단계를 추가하여 조인의 컬렉션 사이드에서 $unset
불필요한 필드를 제거 orders
.
embedded_pipeline.push(doc! { "$unset": ["_id", "product_name", "product_variation"] });
임베디드 파이프라인이 완료되면 $lookup
단계를 기본 집계 파이프라인에 추가합니다. 처리된 조회 필드를 orders
배열 필드에 저장하도록 이 단계를 구성합니다.
pipeline.push(doc! { "$lookup": { "from": "orders", "let": { "prdname": "$name", "prdvartn": "$variation" }, "pipeline": embedded_pipeline, "as": "orders" } });
2020에서 주문한 제품에 대해 일치 단계를 추가합니다.
다음으로, 이전 단계에서 계산된 배열 기반으로 단계를 추가하여 에 주문이 하나 이상 있는 $match
제품만 2020 표시합니다.orders
pipeline.push(doc! { "$match": { "orders": { "$ne": [] } } });
불필요한 필드를 제거 하려면 설정되지 않은 단계를 추가합니다.
마지막으로 단계를 $unset
추가합니다.$unset
단계는 _id
description
결과 문서에서 및 필드를 제거합니다.
pipeline.push(doc! { "$unset": ["_id", "description"] });
집계 결과를 해석합니다.
애그리게이션된 결과에는 두 개의 문서가 포함됩니다. 이 문서는 2020년에 주문이 접수된 제품을 나타냅니다. 각 문서에는 해당 제품의 각 주문에 대한 세부 정보를 나열하는 orders
배열 필드가 포함되어 있습니다.
Document({"name": String("Asus Laptop"), "variation": String("Standard Display"), "category": String("ELECTRONICS"), "orders": Array([Document({"customer_id": String("[email protected]"), "order_date": DateTime(2020-05-30 8:35:52.0 +00:00:00), "value": Double(431.42999267578125)}), Document({"customer_id": String("[email protected]"), "order_date": DateTime(2020-12-26 8:55:46.0 +00:00:00), "value": Double(429.6499938964844)})])}) Document({"name": String("Morphy Richards Food Mixer"), "variation": String("Deluxe"), "category": String("KITCHENWARE"), "orders": Array([Document({"customer_id": String("[email protected]"), "order_date": DateTime(2020-01-01 8:25:37.0 +00:00:00), "value": Double(63.130001068115234)})])})
결과 문서에는 orders
collection 및 products
collection에 있는 문서의 세부 정보가 제품 이름 및 변형으로 결합되어 포함됩니다.
컬렉션을 연결하고 필드를 가져오는 조회 단계를 추가합니다.
파이프라인 의 첫 번째 단계는 단계로,$lookup
각 orders
컬렉션 의 products
두 필드를 기준으로 컬렉션 컬렉션 에 조인합니다. 조회 단계에는 조인을 구성하기 위한 파이프라인 포함되어 있습니다.
포함된 파이프라인 내에서 단계를 추가하여 조인 $match
양쪽에 있는 두 필드의 값을 일치시킵니다. 다음 코드에서는 name
variation
$lookup 단계를 만들때 설정하다 및 필드에 별칭을 사용합니다.
Aggregates.filter( Filters.expr( Filters.and( Document("$eq" -> Seq("$product_name", "$$prdname")), Document("$eq" -> Seq("$product_variation", "$$prdvartn")) ) ) ),
내장된 파이프라인 내에서 에 접수된 주문과 $match
2020 일치하도록 다른 단계를 추가합니다.
Aggregates.filter( Filters.and( Filters.gte("orderdate", dateFormat.parse("2020-01-01T00:00:00")), Filters.lt("orderdate", dateFormat.parse("2021-01-01T00:00:00")) ) ),
포함된 파이프라인 내에서 단계를 추가하여 조인의 컬렉션 사이드에서 $unset
불필요한 필드를 제거 orders
.
Aggregates.unset("_id", "product_name", "product_variation"),
임베디드 파이프라인이 완료되면 $lookup
단계를 기본 집계 파이프라인에 추가합니다. 처리된 조회 필드를 orders
배열 필드에 저장하도록 이 단계를 구성합니다.
Aggregates.lookup( "orders", Seq( Variable("prdname", "$name"), Variable("prdvartn", "$variation"), ), embeddedPipeline, "orders" ),
2020에서 주문한 제품에 대해 일치 단계를 추가합니다.
다음으로, 이전 단계에서 계산된 배열 기반으로 단계를 추가하여 에 주문이 하나 이상 있는 $match
제품만 2020 표시합니다.orders
Aggregates.filter(Filters.ne("orders", Seq())),
불필요한 필드를 제거 하려면 설정되지 않은 단계를 추가합니다.
마지막으로 단계를 $unset
추가합니다.$unset
단계는 _id
description
결과 문서에서 및 필드를 제거합니다.
Aggregates.unset("_id", "description")
집계 결과를 해석합니다.
애그리게이션된 결과에는 두 개의 문서가 포함됩니다. 이 문서는 2020년에 주문이 접수된 제품을 나타냅니다. 각 문서에는 해당 제품의 각 주문에 대한 세부 정보를 나열하는 orders
배열 필드가 포함되어 있습니다.
{"name": "Asus Laptop", "variation": "Standard Display", "category": "ELECTRONICS", "orders": [{"customer_id": "[email protected]", "orderdate": {"$date": "2020-05-30T12:35:52Z"}, "value": 431.43}, {"customer_id": "[email protected]", "orderdate": {"$date": "2020-12-26T13:55:46Z"}, "value": 429.65}]} {"name": "Morphy Richards Food Mixer", "variation": "Deluxe", "category": "KITCHENWARE", "orders": [{"customer_id": "[email protected]", "orderdate": {"$date": "2020-01-01T13:25:37Z"}, "value": 63.13}]}
결과 문서에는 orders
collection 및 products
collection에 있는 문서의 세부 정보가 제품 이름 및 변형으로 결합되어 포함됩니다.