このチュートリアルでは、集計パイプラインを構築し、コレクションに対して集計を実行し、選択した言語を使用して結果を表示する方法を説明します。
このタスクについて
このチュートリアルでは、製品情報を記述するコレクションのデータと、カスタマーの注文を記述する別のコレクションのデータを組み合わせる方法を説明します。結果には、2020 で注文された製品の一覧と、各注文に関する詳細が表示されます。
この集計では、$lookup
を使用して複数フィールド結合を実行します。複数結合フィールドは、2 つのコレクションのドキュメント内に対応するフィールドが複数ある場合に発生します。集計では、対応するフィールドでこれらのドキュメントを照合し、両方の情報を 1 つのドキュメントに結合します。
始める前に
➤ 右上の[ 言語選択 ] ドロップダウンメニューを使用して、以下の例の言語を設定するか、 MongoDB Shell を選択します。
この例では、2 つのコレクションを使用します。
products
は、店舗が販売する商品を説明するドキュメントを含みます。orders
は、店舗内の製品の個々の注文を説明するドキュメントを含みます
注文には1つの製品のみを含めることができます。集計では複数フィールド結合を使用して、製品ドキュメントを、その製品の注文を表すドキュメントと照合します。この集計は、 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デプロイに接続し、サンプルデータをMongoDBに挿入し、集計パイプラインを実行できます。
Tip
ドライバーをインストールして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; }
すべてのチュートリアルで、接続stringプレースホルダーを配置の接続stringに置き換える必要があります。
たとえば、接続stringが "mongodb+srv://mongodb-example:27017"
の場合、接続stringの割り当ては次のようになります。
char *uri = "mongodb+srv://mongodb-example:27017";
コレクションの作成
この例では、2 つのコレクションを使用します。
products
は、店舗が販売する商品を説明するドキュメントを含みます。orders
は、店舗内の製品の個々の注文を説明するドキュメントを含みます
注文には1つの製品のみを含めることができます。集計では複数フィールド結合を使用して、製品ドキュメントを、その製品の注文を表すドキュメントと照合します。この集計は、 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デプロイに接続し、サンプルデータをMongoDBに挿入し、集計パイプラインを実行できます。
Tip
ドライバーをインストールして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; } }
すべてのチュートリアルで、接続stringプレースホルダーを配置の接続stringに置き換える必要があります。
たとえば、接続stringが "mongodb+srv://mongodb-example:27017"
の場合、接続stringの割り当ては次のようになります。
mongocxx::uri uri{"mongodb+srv://mongodb-example:27017"};
コレクションの作成
この例では、2 つのコレクションを使用します。
products
は、店舗が販売する商品を説明するドキュメントを含みます。orders
は、店舗内の製品の個々の注文を説明するドキュメントを含みます
注文には1つの製品のみを含めることができます。集計では複数フィールド結合を使用して、製品ドキュメントを、その製品の注文を表すドキュメントと照合します。この集計は、 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デプロイに接続し、サンプルデータをMongoDBに挿入し、集計パイプラインを実行できます。
Tip
ドライバーをインストールして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); }
すべてのチュートリアルで、接続stringプレースホルダーを配置の接続stringに置き換える必要があります。
Tip
配置の接続文字列を見つける方法については、 C#クイック スタートガイドの「 Atlas で無料階層クラスターを設定する 」のステップを参照してください。
たとえば、接続stringが "mongodb+srv://mongodb-example:27017"
の場合、接続stringの割り当ては次のようになります。
var uri = "mongodb+srv://mongodb-example:27017";
コレクションの作成
この例では、2 つのコレクションを使用します。
products
は、店舗が販売する商品を説明するドキュメントを含みます。orders
は、店舗内の製品の個々の注文を説明するドキュメントを含みます
注文には1つの製品のみを含めることができます。集計では複数フィールド結合を使用して、製品ドキュメントを、その製品の注文を表すドキュメントと照合します。この集計は、 orders
コレクション内のドキュメントの ProductName
フィールドと ProductVariation
フィールドに対応する、products
コレクション内のドキュメントの Name
フィールドと Variation
フィールドによってコレクションを結合します。
まず、products
コレクションと orders
コレクション内のデータをモデル化するためのC#クラスを作成します。
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デプロイに接続し、サンプルデータをMongoDBに挿入し、集計パイプラインを実行できます。
Tip
ドライバーをインストールしてMongoDBに接続する方法については、 「 Go Driver クイック スタートガイド」を参照してください。
Go Driver で集計を実行する方法の詳細については、「 集計ガイド 」を参照してください。
ドライバーをインストールしたら、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)) } }
すべてのチュートリアルで、接続stringプレースホルダーを配置の接続stringに置き換える必要があります。
Tip
配置の接続文字列を見つける方法については、 Goクイック スタートガイドの「 MongoDBクラスターの作成 」ステップを参照してください。
たとえば、接続stringが "mongodb+srv://mongodb-example:27017"
の場合、接続stringの割り当ては次のようになります。
const uri = "mongodb+srv://mongodb-example:27017";
コレクションの作成
この例では、2 つのコレクションを使用します。
products
は、店舗が販売する商品を説明するドキュメントを含みます。orders
は、店舗内の製品の個々の注文を説明するドキュメントを含みます
注文には1つの製品のみを含めることができます。集計では複数フィールド結合を使用して、製品ドキュメントを、その製品の注文を表すドキュメントと照合します。この集計は、 orders
コレクション内のドキュメントの product_name
フィールドと product_variation
フィールドに対応する、products
コレクション内のドキュメントの name
フィールドと variation
フィールドによってコレクションを結合します。
まず、products
コレクションと orders
コレクション内のデータをモデル化するためのGo構造体を作成します。
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デプロイに接続し、サンプルデータをMongoDBに挿入し、集計パイプラインを実行できます。
Tip
ドライバーをインストールしてMongoDBに接続する方法については、 Javaドライバーを使い始める のガイドを参照してください。
Java Sync Driver で集計を実行する方法の詳細については、 集計ガイドを参照してください。
ドライバーをインストールしたら、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()); } } } }
すべてのチュートリアルで、接続stringプレースホルダーを配置の接続stringに置き換える必要があります。
たとえば、接続stringが "mongodb+srv://mongodb-example:27017"
の場合、接続stringの割り当ては次のようになります。
String uri = "mongodb+srv://mongodb-example:27017";
コレクションの作成
この例では、2 つのコレクションを使用します。
products
は、店舗が販売する商品を説明するドキュメントを含みます。orders
は、店舗内の製品の個々の注文を説明するドキュメントを含みます
注文には1つの製品のみを含めることができます。集計では複数フィールド結合を使用して、製品ドキュメントを、その製品の注文を表すドキュメントと照合します。この集計は、 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デプロイに接続し、サンプルデータをMongoDBに挿入し、集計パイプラインを実行できます。
Tip
ドライバーをインストールしてMongoDBに接続する方法については、 Javaドライバーを使い始める のガイドを参照してください。
Java Sync Driver で集計を実行する方法の詳細については、 集計ガイドを参照してください。
ドライバーをインストールしたら、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()); } } } }
すべてのチュートリアルで、接続stringプレースホルダーを配置の接続stringに置き換える必要があります。
たとえば、接続stringが "mongodb+srv://mongodb-example:27017"
の場合、接続stringの割り当ては次のようになります。
String uri = "mongodb+srv://mongodb-example:27017";
コレクションの作成
この例では、2 つのコレクションを使用します。
products
は、店舗が販売する商品を説明するドキュメントを含みます。orders
は、店舗内の製品の個々の注文を説明するドキュメントを含みます
注文には1つの製品のみを含めることができます。集計では複数フィールド結合を使用して、製品ドキュメントを、その製品の注文を表すドキュメントと照合します。この集計は、 orders
コレクション内のドキュメントの product_name
フィールドと product_variation
フィールドに対応する、products
コレクション内のドキュメントの name
フィールドと variation
フィールドによってコレクションを結合します。
まず、products
コレクションと orders
コレクション内のデータをモデル化するためのKotlinデータ クラスを作成します。
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デプロイに接続し、サンプルデータをMongoDBに挿入し、集計パイプラインを実行できます。
Tip
ドライバーをインストールして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);
すべてのチュートリアルで、接続stringプレースホルダーを配置の接続stringに置き換える必要があります。
たとえば、接続stringが "mongodb+srv://mongodb-example:27017"
の場合、接続stringの割り当ては次のようになります。
const uri = "mongodb+srv://mongodb-example:27017";
コレクションの作成
この例では、2 つのコレクションを使用します。
products
は、店舗が販売する商品を説明するドキュメントを含みます。orders
は、店舗内の製品の個々の注文を説明するドキュメントを含みます
注文には1つの製品のみを含めることができます。集計では複数フィールド結合を使用して、製品ドキュメントを、その製品の注文を表すドキュメントと照合します。この集計は、 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デプロイに接続し、サンプルデータをMongoDBに挿入し、集計パイプラインを実行できます。
Tip
ドライバーをインストールしてMongoDBに接続する方法については、 「 Go Driver クイック スタートガイド」を参照してください。
Go Driver で集計を実行する方法の詳細については、「 集計ガイド 」を参照してください。
ドライバーをインストールしたら、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)) } }
すべてのチュートリアルで、接続stringプレースホルダーを配置の接続stringに置き換える必要があります。
Tip
配置の接続文字列を見つける方法については、 Goクイック スタートガイドの「 MongoDBクラスターの作成 」ステップを参照してください。
たとえば、接続stringが "mongodb+srv://mongodb-example:27017"
の場合、接続stringの割り当ては次のようになります。
const uri = "mongodb+srv://mongodb-example:27017";
コレクションの作成
この例では、2 つのコレクションを使用します。
products
は、店舗が販売する商品を説明するドキュメントを含みます。orders
は、店舗内の製品の個々の注文を説明するドキュメントを含みます
注文には1つの製品のみを含めることができます。集計では複数フィールド結合を使用して、製品ドキュメントを、その製品の注文を表すドキュメントと照合します。この集計は、 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デプロイに接続し、サンプルデータをMongoDBに挿入し、集計パイプラインを実行できます。
Tip
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()
すべてのチュートリアルで、接続stringプレースホルダーを配置の接続stringに置き換える必要があります。
たとえば、接続stringが "mongodb+srv://mongodb-example:27017"
の場合、接続stringの割り当ては次のようになります。
uri = "mongodb+srv://mongodb-example:27017"
コレクションの作成
この例では、2 つのコレクションを使用します。
products
は、店舗が販売する商品を説明するドキュメントを含みます。orders
は、店舗内の製品の個々の注文を説明するドキュメントを含みます
注文には1つの製品のみを含めることができます。集計では複数フィールド結合を使用して、製品ドキュメントを、その製品の注文を表すドキュメントと照合します。この集計は、 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デプロイに接続し、サンプルデータをMongoDBに挿入し、集計パイプラインを実行できます。
Tip
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
すべてのチュートリアルで、接続stringプレースホルダーを配置の接続stringに置き換える必要があります。
たとえば、接続stringが "mongodb+srv://mongodb-example:27017"
の場合、接続stringの割り当ては次のようになります。
uri = "mongodb+srv://mongodb-example:27017"
コレクションの作成
この例では、2 つのコレクションを使用します。
products
は、店舗が販売する商品を説明するドキュメントを含みます。orders
は、店舗内の製品の個々の注文を説明するドキュメントを含みます
注文には1つの製品のみを含めることができます。集計では複数フィールド結合を使用して、製品ドキュメントを、その製品の注文を表すドキュメントと照合します。この集計は、 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デプロイに接続し、サンプルデータをMongoDBに挿入し、集計パイプラインを実行できます。
Tip
ドライバーをインストールして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(()) }
すべてのチュートリアルで、接続stringプレースホルダーを配置の接続stringに置き換える必要があります。
たとえば、接続stringが "mongodb+srv://mongodb-example:27017"
の場合、接続stringの割り当ては次のようになります。
let uri = "mongodb+srv://mongodb-example:27017";
コレクションの作成
この例では、2 つのコレクションを使用します。
products
は、店舗が販売する商品を説明するドキュメントを含みます。orders
は、店舗内の製品の個々の注文を説明するドキュメントを含みます
注文には1つの製品のみを含めることができます。集計では複数フィールド結合を使用して、製品ドキュメントを、その製品の注文を表すドキュメントと照合します。この集計は、 orders
コレクション内のドキュメントの product_name
フィールドと product_variation
フィールドに対応する、products
コレクション内のドキュメントの name
フィールドと variation
フィールドによってコレクションを結合します。
まず、products
コレクションと orders
コレクション内のデータをモデル化するためのRust構造体を作成します。
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?;
テンプレート アプリの作成
集計チュートリアルに従う前に、新しいScalaアプリを設定する必要があります。このアプリを使用して、 MongoDBデプロイに接続し、サンプルデータをMongoDBに挿入し、集計パイプラインを実行できます。
Tip
ドライバーをインストールしてMongoDBに接続する方法については、 「 Scalaドライバーを使い始める 」ガイドを参照してください。
Scalaドライバーで集計を実行する方法の詳細については、「 集計ガイド 」を参照してください。
ドライバーをインストールしたら、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() } }
すべてのチュートリアルで、接続stringプレースホルダーを配置の接続stringに置き換える必要があります。
たとえば、接続stringが "mongodb+srv://mongodb-example:27017"
の場合、接続stringの割り当ては次のようになります。
val uri = "mongodb+srv://mongodb-example:27017"
コレクションの作成
この例では、2 つのコレクションを使用します。
products
は、店舗が販売する商品を説明するドキュメントを含みます。orders
は、店舗内の製品の個々の注文を説明するドキュメントを含みます
注文には1つの製品のみを含めることができます。集計では複数フィールド結合を使用して、製品ドキュメントを、その製品の注文を表すドキュメントと照合します。この集計は、 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), )
手順
次の手順は、集計パイプラインを作成して実行し、複数のフィールドのコレクションを結合する方法を示しています。
ルックアップ ステージで使用する埋め込みパイプラインを作成します。
パイプラインの最初のステージは、各コレクションの 2 つのフィールドで 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"] } ] )
集計結果の解釈
集計された結果には 2 つのドキュメントが含まれます。ドキュメントは、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
2 つのフィールドで コレクションと コレクションに結合する ステージです。ルックアップステージには、結合を構成するための埋め込みパイプラインが含まれています。
$match
埋め込みパイプラインを作成し、結合の両方にある 2 つのフィールドの値を一致させるために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配列に基づいて、 に少なくとも 1 回の注文がある製品のみを表示する ステージを追加します。orders
"{", "$match", "{", "orders", "{", "$ne", "[", "]", "}", "}", "}",
不要なフィールドを削除するには、設定されていない ステージを追加します。
最後に、$unset
ステージを追加します。$unset
ステージでは、結果ドキュメントから フィールドと フィールドが削除されます。_id
description
"{", "$unset", "[", BCON_UTF8("_id"), BCON_UTF8("description"), "]", "}",
集計パイプラインを実行します。
次のコードをアプリケーションの末尾に追加して、 products
コレクションで集計を実行します。
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
Tip
上記のコマンドを 1 回の呼び出しで実行中て接続エラーが発生した場合は、個別に実行できます。
集計結果の解釈
集計された結果には 2 つのドキュメントが含まれています。 ドキュメントは、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
コレクションとproducts
コレクション内のドキュメントの詳細が、製品名とバリエーションで結合されたものが含まれます。
コレクションをリンクし、フィールドをインポートするために、ルックアップ ステージを追加します。
パイプラインの最初のステージは、各コレクションの$lookup
orders
products
2 つのフィールドで コレクションと コレクションに結合する ステージです。ルックアップステージには、結合を構成するための埋め込みパイプラインが含まれています。
$match
埋め込みパイプライン内に、結合の両方にある 2 つのフィールドの値を一致させるために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配列に基づいて、 に少なくとも 1 回の注文がある製品のみを表示する ステージを追加します。orders
pipeline.match(bsoncxx::from_json(R"({ "orders": { "$ne": [] } })"));
不要なフィールドを削除するには、設定されていない ステージを追加します。
最後に、$unset
ステージを追加します。$unset
ステージでは、結果ドキュメントから フィールドと フィールドが削除されます。_id
description
pipeline.append_stage(bsoncxx::from_json(R"({ "$unset": ["_id", "description"] })"));
集計結果の解釈
集計された結果には 2 つのドキュメントが含まれています。 ドキュメントは、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
コレクションとproducts
コレクション内のドキュメントの詳細が、製品名とバリエーションで結合されたものが含まれます。
コレクションをリンクし、フィールドをインポートするために、ルックアップ ステージを追加します。
パイプラインの最初のステージは、各コレクションの$lookup
orders
products
2 つのフィールドで コレクションと コレクションに結合する ステージです。ルックアップステージには、結合を構成するための埋め込みパイプラインが含まれています。
$match
埋め込みパイプラインをインスタンス化し、結合の両方にある 2 つのフィールドの値を一致させるために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配列に基づいて、 に少なくとも 1 回の注文がある製品のみを表示するOrders
ステージを追加します。
.Match(Builders<BsonDocument>.Filter.Ne("Orders", new BsonArray()))
不要なフィールドを削除するには、プロジェクションステージを追加します。
最後に、$project
ステージを追加します。$project
ステージでは、結果ドキュメントから フィールドと フィールドが削除されます。_id
Description
.Project(Builders<BsonDocument>.Projection .Exclude("_id") .Exclude("Description") );
集計を実行し、結果を解釈します。
最後に、IDE でアプリケーションを実行し、結果を調べます。
集計された結果には 2 つのドキュメントが含まれています。 ドキュメントは、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
コレクションとproducts
コレクション内のドキュメントの詳細が、製品名とバリエーションで結合されたものが含まれます。
コレクションをリンクし、フィールドをインポートするために、ルックアップ ステージを追加します。
パイプラインの最初のステージは、各コレクションの$lookup
orders
products
2 つのフィールドで コレクションと コレクションに結合する ステージです。ルックアップステージには、結合を構成するための埋め込みパイプラインが含まれています。
$match
埋め込みパイプライン内に、結合の両方にある 2 つのフィールドの値を一致させるために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配列に基づいて、 に少なくとも 1 回の注文がある製品のみを表示する ステージを追加します。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"}}, }
集計結果の解釈
集計された結果には 2 つのドキュメントが含まれています。 ドキュメントは、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
コレクションとproducts
コレクション内のドキュメントの詳細が、製品名とバリエーションで結合されたものが含まれます。
コレクションをリンクし、フィールドをインポートするために、ルックアップ ステージを追加します。
パイプラインの最初のステージは、各コレクションの$lookup
orders
products
2 つのフィールドで コレクションと コレクションに結合する ステージです。ルックアップステージには、結合を構成するための埋め込みパイプラインが含まれています。
$match
埋め込みパイプライン内に、結合の両方にある 2 つのフィールドの値を一致させるために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配列に基づいて、 に少なくとも 1 回の注文がある製品のみを表示する ステージを追加します。orders
pipeline.add(Aggregates.match( Filters.ne("orders", new ArrayList<>()) ));
不要なフィールドを削除するには、設定されていない ステージを追加します。
最後に、$unset
ステージを追加します。$unset
ステージでは、結果ドキュメントから フィールドと フィールドが削除されます。_id
description
pipeline.add(Aggregates.unset("_id", "description"));
集計結果の解釈
集計された結果には 2 つのドキュメントが含まれています。 ドキュメントは、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
コレクションとproducts
コレクション内のドキュメントの詳細が、製品名とバリエーションで結合されたものが含まれます。
コレクションをリンクし、フィールドをインポートするために、ルックアップ ステージを追加します。
パイプラインの最初のステージは、各コレクションの$lookup
orders
products
2 つのフィールドで コレクションと コレクションに結合する ステージです。ルックアップステージには、結合を構成するための埋め込みパイプラインが含まれています。
$match
埋め込みパイプライン内に、結合の両方にある 2 つのフィールドの値を一致させるために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配列に基づいて、 に少なくとも 1 回の注文がある製品のみを表示する ステージを追加します。orders
pipeline.add( Aggregates.match( Filters.ne("orders", mutableListOf<Document>()) ) )
不要なフィールドを削除するには、設定されていない ステージを追加します。
最後に、$unset
ステージを追加します。$unset
ステージでは、結果ドキュメントから フィールドと フィールドが削除されます。_id
description
pipeline.add(Aggregates.unset("_id", "description"))
集計結果の解釈
集計された結果には 2 つのドキュメントが含まれています。 ドキュメントは、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
コレクションとproducts
コレクション内のドキュメントの詳細が、製品名とバリエーションで結合されたものが含まれます。
コレクションをリンクし、フィールドをインポートするために、ルックアップ ステージを追加します。
パイプラインの最初のステージは、各コレクションの$lookup
orders
products
2 つのフィールドで コレクションと コレクションに結合する ステージです。ルックアップステージには、結合を構成するための埋め込みパイプラインが含まれています。
$match
埋め込みパイプライン内に、結合の両方にある 2 つのフィールドの値を一致させるために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配列に基づいて、 に少なくとも 1 回の注文がある製品のみを表示する ステージを追加します。orders
pipeline.push({ $match: { orders: { $ne: [] }, }, });
不要なフィールドを削除するには、設定されていない ステージを追加します。
最後に、$unset
ステージを追加します。$unset
ステージでは、結果ドキュメントから フィールドと フィールドが削除されます。_id
description
pipeline.push({ $unset: ["_id", "description"], });
集計結果の解釈
集計された結果には 2 つのドキュメントが含まれています。 ドキュメントは、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
コレクションとproducts
コレクション内のドキュメントの詳細が、製品名とバリエーションで結合されたものが含まれます。
コレクションをリンクし、フィールドをインポートするために、ルックアップ ステージを追加します。
パイプラインの最初のステージは、各コレクションの 2$lookup
つのフィールドでorders
コレクションとproducts
コレクションに結合する ステージです。ルックアップステージには、結合を構成するための埋め込みパイプラインが含まれています。まず、 埋め込みパイプラインを作成します。
$embeddedPipeline = new Pipeline( // Add stages within embedded pipeline. };
$match
埋め込みパイプライン内に、結合の両方にある 2 つのフィールドの値を一致させるために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配列に基づいて、 に少なくとも 1 回の注文がある製品のみを表示する ステージを追加します。orders
Stage::match( orders: Query::ne([]) ),
不要なフィールドを削除するには、設定されていない ステージを追加します。
最後に、$unset
ステージを追加します。$unset
ステージでは、結果ドキュメントから フィールドと フィールドが削除されます。_id
description
Stage::unset('_id', 'description')
集計結果の解釈
集計された結果には 2 つのドキュメントが含まれています。 ドキュメントは、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
コレクションとproducts
コレクション内のドキュメントの詳細が、製品名とバリエーションで結合されたものが含まれます。
コレクションをリンクし、フィールドをインポートするために、ルックアップ ステージを追加します。
パイプラインの最初のステージは、各コレクションの$lookup
orders
products
2 つのフィールドで コレクションと コレクションに結合する ステージです。ルックアップステージには、結合を構成するための埋め込みパイプラインが含まれています。
$match
埋め込みパイプライン内に、結合の両方にある 2 つのフィールドの値を一致させるために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配列に基づいて、 に少なくとも 1 回の注文がある製品のみを表示する ステージを追加します。orders
pipeline.append({"$match": {"orders": {"$ne": []}}})
不要なフィールドを削除するには、設定されていない ステージを追加します。
最後に、$unset
ステージを追加します。$unset
ステージでは、結果ドキュメントから フィールドと フィールドが削除されます。_id
description
pipeline.append({"$unset": ["_id", "description"]})
集計結果の解釈
集計された結果には 2 つのドキュメントが含まれています。 ドキュメントは、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
コレクションとproducts
コレクション内のドキュメントの詳細が、製品名とバリエーションで結合されたものが含まれます。
コレクションをリンクし、フィールドをインポートするために、ルックアップ ステージを追加します。
パイプラインの最初のステージは、各コレクションの$lookup
orders
products
2 つのフィールドで コレクションと コレクションに結合する ステージです。ルックアップステージには、結合を構成するための埋め込みパイプラインが含まれています。
$match
埋め込みパイプライン内に、結合の両方にある 2 つのフィールドの値を一致させるために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配列に基づいて、 に少なくとも 1 回の注文がある製品のみを表示する ステージを追加します。orders
{ "$match": { orders: { "$ne": [] }, }, },
不要なフィールドを削除するには、設定されていない ステージを追加します。
最後に、$unset
ステージを追加します。$unset
ステージでは、結果ドキュメントから フィールドと フィールドが削除されます。_id
description
{ "$unset": ["_id", "description"], },
集計結果の解釈
集計された結果には 2 つのドキュメントが含まれています。 ドキュメントは、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
コレクションとproducts
コレクション内のドキュメントの詳細が、製品名とバリエーションで結合されたものが含まれます。
コレクションをリンクし、フィールドをインポートするために、ルックアップ ステージを追加します。
パイプラインの最初のステージは、各コレクションの$lookup
orders
products
2 つのフィールドで コレクションと コレクションに結合する ステージです。ルックアップステージには、結合を構成するための埋め込みパイプラインが含まれています。
$match
埋め込みパイプライン内に、結合の両方にある 2 つのフィールドの値を一致させるために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配列に基づいて、 に少なくとも 1 回の注文がある製品のみを表示する ステージを追加します。orders
pipeline.push(doc! { "$match": { "orders": { "$ne": [] } } });
不要なフィールドを削除するには、設定されていない ステージを追加します。
最後に、$unset
ステージを追加します。$unset
ステージでは、結果ドキュメントから フィールドと フィールドが削除されます。_id
description
pipeline.push(doc! { "$unset": ["_id", "description"] });
集計結果の解釈
集計された結果には 2 つのドキュメントが含まれています。 ドキュメントは、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
コレクションとproducts
コレクション内のドキュメントの詳細が、製品名とバリエーションで結合されたものが含まれます。
コレクションをリンクし、フィールドをインポートするために、ルックアップ ステージを追加します。
パイプラインの最初のステージは、各コレクションの$lookup
orders
products
2 つのフィールドで コレクションと コレクションに結合する ステージです。ルックアップステージには、結合を構成するための埋め込みパイプラインが含まれています。
$match
埋め込みパイプライン内に、結合の両方にある 2 つのフィールドの値を一致させるために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配列に基づいて、 に少なくとも 1 回の注文がある製品のみを表示する ステージを追加します。orders
Aggregates.filter(Filters.ne("orders", Seq())),
不要なフィールドを削除するには、設定されていない ステージを追加します。
最後に、$unset
ステージを追加します。$unset
ステージでは、結果ドキュメントから フィールドと フィールドが削除されます。_id
description
Aggregates.unset("_id", "description")
集計結果の解釈
集計された結果には 2 つのドキュメントが含まれています。 ドキュメントは、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
コレクションとproducts
コレクション内のドキュメントの詳細が、製品名とバリエーションで結合されたものが含まれます。