Docs Menu
Docs Home
/
データベース マニュアル
/ / /

グループと合計データ

このチュートリアルでは、集計パイプラインを構築し、コレクションに対して集計を実行し、選択した言語を使用して結果を表示する方法を説明します。

このチュートリアルでは、カスタマーの注文データをグループ化して分析する方法を説明します。結果には、2020 で商品を購入したカスタマーのリストが表示され、2020 における各カスタマーの注文履歴が含まれます。

集計パイプラインでは、次の操作が実行されます。

  • フィールド値でドキュメントのサブセットと一致

  • ドキュメントを共通のフィールド値でグループ化

  • 各結果ドキュメントに計算フィールドを追加します


右上の[ 言語選択 ] ドロップダウンメニューを使用して、以下の例の言語を設定するか、 MongoDB Shell を選択します。


この例では、個々の製品注文を説明するドキュメントを含む ordersコレクションを使用します。各注文は 1 人のカスタマーのみに対応するため、集計では注文ドキュメントがカスタマーのメールアドレスを含む customer_idフィールドでグループ化されます。

ordersコレクションを作成するには、insertMany() メソッドを使用します。

db.orders.deleteMany({})
db.orders.insertMany( [
{
customer_id: "[email protected]",
orderdate: new Date("2020-05-30T08:35:52Z"),
value: 231,
},
{
customer_id: "[email protected]",
orderdate: new Date("2020-01-13T09:32:07Z"),
value: 99,
},
{
customer_id: "[email protected]",
orderdate: new Date("2020-01-01T08:25:37Z"),
value: 63,
},
{
customer_id: "[email protected]",
orderdate: new Date("2019-05-28T19:13:32Z"),
value: 2,
},
{
customer_id: "[email protected]",
orderdate: new Date("2020-11-23T22:56:53Z"),
value: 187,
},
{
customer_id: "[email protected]",
orderdate: new Date("2020-08-18T23:04:48Z"),
value: 4,
},
{
customer_id: "[email protected]",
orderdate: new Date("2020-12-26T08:55:46Z"),
value: 4,
},
{
customer_id: "[email protected]",
orderdate: new Date("2021-02-29T07:49:32Z"),
value: 1024,
},
{
customer_id: "[email protected]",
orderdate: new Date("2020-10-03T13:49:44Z"),
value: 102,
}
] )

この集計チュートリアルに従う前に、新しいCアプリを設定する必要があります。このアプリを使用して、 MongoDBデプロイに接続し、サンプルデータをMongoDBに挿入し、集計パイプラインを実行できます。

Tip

ドライバーをインストールしてMongoDBに接続する方法については、「 Cドライバーを使い始める 」ガイドを参照してください。

Cドライバーで集計を実行する方法の詳細については、「 集計ガイド 」を参照してください。

ドライバーをインストールしたら、agg-tutorial.cというファイルを作成します。このファイルに次のコードを貼り付けて、集計チュートリアル用のアプリテンプレートを作成します。

重要

次のコードでは、コードコメントを読み取って、次のチュートリアルで変更する必要があるコードのセクションを見つけます。

変更せずにコードを実行しようとすると、接続エラーが発生します。

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

すべてのチュートリアルで、接続stringプレースホルダーを配置の接続stringに置き換える必要があります。

Tip

配置の接続文字列を見つける方法については、 Cスタートガイドの「 接続文字列の作成 」ステップを参照してください。

たとえば、接続stringが "mongodb+srv://mongodb-example:27017" の場合、接続stringの割り当ては次のようになります。

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

この例では、個々の製品の注文を説明するドキュメントを含む ordersコレクションを使用しています。各注文は 1 人のカスタマーのみに対応するため、集計ではカスタマーのメールアドレスが含まれる customer_idフィールドで注文ドキュメントがグループ集計れます。

ordersコレクションを作成し、サンプルデータを挿入するには、次のコードをアプリケーションに追加します。

mongoc_collection_t *orders = mongoc_client_get_collection(client, "agg_tutorials_db", "orders");
{
bson_t *filter = bson_new();
bson_error_t error;
if (!mongoc_collection_delete_many(orders, filter, NULL, NULL, &error))
{
fprintf(stderr, "Delete error: %s\n", error.message);
}
bson_destroy(filter);
}
{
size_t num_docs = 9;
bson_t *docs[num_docs];
docs[0] = BCON_NEW(
"customer_id", BCON_UTF8("[email protected]"),
"orderdate", BCON_DATE_TIME(1590825352000UL), // 2020-05-30T08:35:52Z
"value", BCON_INT32(231));
docs[1] = BCON_NEW(
"customer_id", BCON_UTF8("[email protected]"),
"orderdate", BCON_DATE_TIME(1578904327000UL), // 2020-01-13T09:32:07Z
"value", BCON_INT32(99));
docs[2] = BCON_NEW(
"customer_id", BCON_UTF8("[email protected]"),
"orderdate", BCON_DATE_TIME(1577865937000UL), // 2020-01-01T08:25:37Z
"value", BCON_INT32(63));
docs[3] = BCON_NEW(
"customer_id", BCON_UTF8("[email protected]"),
"orderdate", BCON_DATE_TIME(1559061212000UL), // 2019-05-28T19:13:32Z
"value", BCON_INT32(2));
docs[4] = BCON_NEW(
"customer_id", BCON_UTF8("[email protected]"),
"orderdate", BCON_DATE_TIME(1606171013000UL), // 2020-11-23T22:56:53Z
"value", BCON_INT32(187));
docs[5] = BCON_NEW(
"customer_id", BCON_UTF8("[email protected]"),
"orderdate", BCON_DATE_TIME(1597793088000UL), // 2020-08-18T23:04:48Z
"value", BCON_INT32(4));
docs[6] = BCON_NEW(
"customer_id", BCON_UTF8("[email protected]"),
"orderdate", BCON_DATE_TIME(1608963346000UL), // 2020-12-26T08:55:46Z
"value", BCON_INT32(4));
docs[7] = BCON_NEW(
"customer_id", BCON_UTF8("[email protected]"),
"orderdate", BCON_DATE_TIME(1614496172000UL), // 2021-02-28T07:49:32Z
"value", BCON_INT32(1024));
docs[8] = BCON_NEW(
"customer_id", BCON_UTF8("[email protected]"),
"orderdate", BCON_DATE_TIME(1601722184000UL), // 2020-10-03T13:49:44Z
"value", BCON_INT32(102));
bson_error_t error;
if (!mongoc_collection_insert_many(orders, (const bson_t **)docs, num_docs, NULL, NULL, &error))
{
fprintf(stderr, "Insert error: %s\n", error.message);
}
for (int i = 0; i < num_docs; i++)
{
bson_destroy(docs[i]);
}
}

集計チュートリアルに従う前に、新しいC++アプリを設定する必要があります。このアプリを使用して、 MongoDBデプロイに接続し、サンプルデータをMongoDBに挿入し、集計パイプラインを実行できます。

Tip

ドライバーをインストールしてMongoDBに接続する方法については、 「 C++を使い始める 」チュートリアルを参照してください。

C++ドライバーの使用の詳細については、 APIドキュメント を参照してください。

C++ドライバーで集計を実行する方法の詳細については、「 集計ガイド 」を参照してください。

ドライバーをインストールしたら、agg-tutorial.cppというファイルを作成します。このファイルに次のコードを貼り付けて、集計チュートリアル用のアプリテンプレートを作成します。

重要

次のコードでは、コードコメントを読み取って、次のチュートリアルで変更する必要があるコードのセクションを見つけます。

変更せずにコードを実行しようとすると、接続エラーが発生します。

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

すべてのチュートリアルで、接続stringプレースホルダーを配置の接続stringに置き換える必要があります。

Tip

配置の接続文字列を見つける方法については、 C++を使い始める チュートリアルの「 接続文字列の作成 」ステップを参照してください。

たとえば、接続stringが "mongodb+srv://mongodb-example:27017" の場合、接続stringの割り当ては次のようになります。

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

この例では、個々の製品の注文を説明するドキュメントを含む ordersコレクションを使用しています。各注文は 1 人のカスタマーのみに対応するため、集計ではカスタマーのメールアドレスが含まれる customer_idフィールドで注文ドキュメントがグループ集計れます。

ordersコレクションを作成し、サンプルデータを挿入するには、次のコードをアプリケーションに追加します。

auto orders = db["orders"];
std::vector<bsoncxx::document::value> docs = {
bsoncxx::from_json(R"({
"customer_id": "[email protected]",
"orderdate": {"$date": 1590821752000},
"value": 231
})"),
bsoncxx::from_json(R"({
"customer_id": "[email protected]",
"orderdate": {"$date": 1578901927},
"value": 99
})"),
bsoncxx::from_json(R"({
"customer_id": "[email protected]",
"orderdate": {"$date": 1577861137},
"value": 63
})"),
bsoncxx::from_json(R"({
"customer_id": "[email protected]",
"orderdate": {"$date": 1559076812},
"value": 2
})"),
bsoncxx::from_json(R"({
"customer_id": "[email protected]",
"orderdate": {"$date": 1606172213},
"value": 187
})"),
bsoncxx::from_json(R"({
"customer_id": "[email protected]",
"orderdate": {"$date": 1597794288},
"value": 4
})"),
bsoncxx::from_json(R"({
"customer_id": "[email protected]",
"orderdate": {"$date": 1608972946000},
"value": 4
})"),
bsoncxx::from_json(R"({
"customer_id": "[email protected]",
"orderdate": {"$date": 1614570572},
"value": 1024
})"),
bsoncxx::from_json(R"({
"customer_id": "[email protected]",
"orderdate": {"$date": 1601722184000},
"value": 102
})")
};
auto result = orders.insert_many(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";

この例では、個々の製品の注文を説明するドキュメントを含む ordersコレクションを使用しています。各注文は 1 人のカスタマーのみに対応するため、集計ではカスタマーのメールアドレスが含まれる CustomerIdフィールドで注文ドキュメントがグループ集計れます。

まず、ordersコレクション内のデータをモデル化するためのC#クラスを作成します。

public class Order
{
[BsonId]
public ObjectId Id { get; set; }
public string CustomerId { get; set; }
public DateTime OrderDate { get; set; }
public int Value { get; set; }
}

ordersコレクションを作成し、サンプルデータを挿入するには、次のコードをアプリケーションに追加します。

var orders = aggDB.GetCollection<Order>("orders");
orders.DeleteMany(Builders<Order>.Filter.Empty);
orders.InsertMany(new List<Order>
{
new Order
{
CustomerId = "[email protected]",
OrderDate = DateTime.Parse("2020-05-30T08:35:52Z"),
Value = 231
},
new Order
{
CustomerId = "[email protected]",
OrderDate = DateTime.Parse("2020-01-13T09:32:07Z"),
Value = 99
},
new Order
{
CustomerId = "[email protected]",
OrderDate = DateTime.Parse("2020-01-01T08:25:37Z"),
Value = 63
},
new Order
{
CustomerId = "[email protected]",
OrderDate = DateTime.Parse("2019-05-28T19:13:32Z"),
Value = 2
},
new Order
{
CustomerId = "[email protected]",
OrderDate = DateTime.Parse("2020-11-23T22:56:53Z"),
Value = 187
},
new Order
{
CustomerId = "[email protected]",
OrderDate = DateTime.Parse("2020-08-18T23:04:48Z"),
Value = 4
},
new Order
{
CustomerId = "[email protected]",
OrderDate = DateTime.Parse("2020-12-26T08:55:46Z"),
Value = 4
},
new Order
{
CustomerId = "[email protected]",
OrderDate = DateTime.Parse("2021-02-28T07:49:32Z"),
Value = 1024
},
new Order
{
CustomerId = "[email protected]",
OrderDate = DateTime.Parse("2020-10-03T13:49:44Z"),
Value = 102
}
});

この集計チュートリアルに従う前に、新しい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";

この例では、個々の製品の注文を説明するドキュメントを含む ordersコレクションを使用しています。各注文は 1 人のカスタマーのみに対応するため、集計ではカスタマーのメールアドレスが含まれる customer_idフィールドで注文ドキュメントがグループ集計れます。

まず、 Go構造体を作成して、ordersコレクション内のデータをモデル化します。

type Order struct {
CustomerID string `bson:"customer_id,omitempty"`
OrderDate bson.DateTime `bson:"orderdate"`
Value int `bson:"value"`
}

ordersコレクションを作成し、サンプルデータを挿入するには、次のコードをアプリケーションに追加します。

orders := aggDB.Collection("orders")
orders.DeleteMany(context.TODO(), bson.D{})
_, err = orders.InsertMany(context.TODO(), []interface{}{
Order{
CustomerID: "[email protected]",
OrderDate: bson.NewDateTimeFromTime(time.Date(2020, 5, 30, 8, 35, 53, 0, time.UTC)),
Value: 231,
},
Order{
CustomerID: "[email protected]",
OrderDate: bson.NewDateTimeFromTime(time.Date(2020, 1, 13, 9, 32, 7, 0, time.UTC)),
Value: 99,
},
Order{
CustomerID: "[email protected]",
OrderDate: bson.NewDateTimeFromTime(time.Date(2020, 1, 01, 8, 25, 37, 0, time.UTC)),
Value: 63,
},
Order{
CustomerID: "[email protected]",
OrderDate: bson.NewDateTimeFromTime(time.Date(2019, 5, 28, 19, 13, 32, 0, time.UTC)),
Value: 2,
},
Order{
CustomerID: "[email protected]",
OrderDate: bson.NewDateTimeFromTime(time.Date(2020, 11, 23, 22, 56, 53, 0, time.UTC)),
Value: 187,
},
Order{
CustomerID: "[email protected]",
OrderDate: bson.NewDateTimeFromTime(time.Date(2020, 8, 18, 23, 4, 48, 0, time.UTC)),
Value: 4,
},
Order{
CustomerID: "[email protected]",
OrderDate: bson.NewDateTimeFromTime(time.Date(2020, 12, 26, 8, 55, 46, 0, time.UTC)),
Value: 4,
},
Order{
CustomerID: "[email protected]",
OrderDate: bson.NewDateTimeFromTime(time.Date(2021, 2, 29, 7, 49, 32, 0, time.UTC)),
Value: 1024,
},
Order{
CustomerID: "[email protected]",
OrderDate: bson.NewDateTimeFromTime(time.Date(2020, 10, 3, 13, 49, 44, 0, time.UTC)),
Value: 102,
},
})
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に置き換える必要があります。

Tip

配置の接続文字列を見つける方法については、 Java Sync クイック スタートガイドの「 接続文字列の作成 」ステップを参照してください。

たとえば、接続stringが "mongodb+srv://mongodb-example:27017" の場合、接続stringの割り当ては次のようになります。

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

この例では、個々の製品の注文を説明するドキュメントを含む ordersコレクションを使用しています。各注文は 1 人のカスタマーのみに対応するため、集計ではカスタマーのメールアドレスが含まれる customer_idフィールドで注文ドキュメントがグループ集計れます。

ordersコレクションを作成し、サンプルデータを挿入するには、次のコードをアプリケーションに追加します。

MongoCollection<Document> orders = aggDB.getCollection("orders");
orders.deleteMany(Filters.empty());
orders.insertMany(
Arrays.asList(
new Document("customer_id", "[email protected]")
.append("orderdate", LocalDateTime.parse("2020-05-30T08:35:52"))
.append("value", 231),
new Document("customer_id", "[email protected]")
.append("orderdate", LocalDateTime.parse("2020-01-13T09:32:07"))
.append("value", 99),
new Document("customer_id", "[email protected]")
.append("orderdate", LocalDateTime.parse("2020-01-01T08:25:37"))
.append("value", 63),
new Document("customer_id", "[email protected]")
.append("orderdate", LocalDateTime.parse("2019-05-28T19:13:32"))
.append("value", 2),
new Document("customer_id", "[email protected]")
.append("orderdate", LocalDateTime.parse("2020-11-23T22:56:53"))
.append("value", 187),
new Document("customer_id", "[email protected]")
.append("orderdate", LocalDateTime.parse("2020-08-18T23:04:48"))
.append("value", 4),
new Document("customer_id", "[email protected]")
.append("orderdate", LocalDateTime.parse("2020-12-26T08:55:46"))
.append("value", 4),
new Document("customer_id", "[email protected]")
.append("orderdate", LocalDateTime.parse("2021-02-28T07:49:32"))
.append("value", 1024),
new Document("customer_id", "[email protected]")
.append("orderdate", LocalDateTime.parse("2020-10-03T13:49:44"))
.append("value", 102)
)
);

集計チュートリアルに従う前に、新しいKotlinアプリを設定する必要があります。このアプリを使用して、 MongoDBデプロイに接続し、サンプルデータをMongoDBに挿入し、集計パイプラインを実行できます。

Tip

ドライバーをインストールしてMongoDBに接続する方法については、「 Kotlinドライバー クイック スタートガイド 」を参照してください。

Kotlinドライバーで集計を実行する方法の詳細については、「 集計ガイド 」を参照してください。

ドライバーに加えて、次の依存関係も build.gradle.ktsファイルに追加し、プロジェクトを再読み込みする 必要があります。

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

ドライバーをインストールしたら、AggTutorial.ktというファイルを作成します。このファイルに次のコードを貼り付けて、集計チュートリアル用のアプリテンプレートを作成します。

重要

次のコードでは、コードコメントを読み取って、次のチュートリアルで変更する必要があるコードのセクションを見つけます。

変更せずにコードを実行しようとすると、接続エラーが発生します。

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

すべてのチュートリアルで、接続stringプレースホルダーを配置の接続stringに置き換える必要があります。

Tip

配置の接続文字列を見つける方法については、 Kotlinドライバー クイック スタートガイドの「 クラスターへの接続 」ステップを参照してください。

たとえば、接続stringが "mongodb+srv://mongodb-example:27017" の場合、接続stringの割り当ては次のようになります。

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

この例では、個々の製品の注文を説明するドキュメントを含む ordersコレクションを使用しています。各注文は 1 人のカスタマーのみに対応するため、集計ではカスタマーのメールアドレスが含まれる customer_idフィールドで注文ドキュメントがグループ集計れます。

まず、ordersコレクション内のデータをモデル化するためのKotlinデータクラスを作成します。

@Serializable
data class Order(
val customerID: String,
@Contextual val orderDate: LocalDateTime,
val value: Int
)

ordersコレクションを作成し、サンプルデータを挿入するには、次のコードをアプリケーションに追加します。

val orders = aggDB.getCollection<Order>("orders")
orders.deleteMany(Filters.empty())
orders.insertMany(
listOf(
Order("[email protected]", LocalDateTime.parse("2020-05-30T08:35:52"), 231),
Order("[email protected]", LocalDateTime.parse("2020-01-13T09:32:07"), 99),
Order("[email protected]", LocalDateTime.parse("2020-01-01T08:25:37"), 63),
Order("[email protected]", LocalDateTime.parse("2019-05-28T19:13:32"), 2),
Order("[email protected]", LocalDateTime.parse("2020-11-23T22:56:53"), 187),
Order("[email protected]", LocalDateTime.parse("2020-08-18T23:04:48"), 4),
Order("[email protected]", LocalDateTime.parse("2020-12-26T08:55:46"), 4),
Order("[email protected]", LocalDateTime.parse("2021-02-28T07:49:32"), 1024),
Order("[email protected]", LocalDateTime.parse("2020-10-03T13:49:44"), 102)
)
)

この集計チュートリアルに従う前に、新しい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に置き換える必要があります。

Tip

デプロイメントの接続文字列を見つける方法については、 Node.jsクイック スタートガイドの「 接続文字列の作成 」ステップを参照してください。

たとえば、接続stringが "mongodb+srv://mongodb-example:27017" の場合、接続stringの割り当ては次のようになります。

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

この例では、個々の製品の注文を説明するドキュメントを含む ordersコレクションを使用しています。各注文は 1 人のカスタマーのみに対応するため、集計ではカスタマーのメールアドレスが含まれる customer_idフィールドで注文ドキュメントがグループ集計れます。

ordersコレクションを作成し、サンプルデータを挿入するには、次のコードをアプリケーションに追加します。

const orders = aggDB.collection("orders");
await orders.deleteMany({});
await orders.insertMany([
{
customer_id: "[email protected]",
orderdate: new Date("2020-05-30T08:35:52Z"),
value: 231,
},
{
customer_id: "[email protected]",
orderdate: new Date("2020-01-13T09:32:07Z"),
value: 99,
},
{
customer_id: "[email protected]",
orderdate: new Date("2020-01-01T08:25:37Z"),
value: 63,
},
{
customer_id: "[email protected]",
orderdate: new Date("2019-05-28T19:13:32Z"),
value: 2,
},
{
customer_id: "[email protected]",
orderdate: new Date("2020-11-23T22:56:53Z"),
value: 187,
},
{
customer_id: "[email protected]",
orderdate: new Date("2020-08-18T23:04:48Z"),
value: 4,
},
{
customer_id: "[email protected]",
orderdate: new Date("2020-12-26T08:55:46Z"),
value: 4,
},
{
customer_id: "[email protected]",
orderdate: new Date("2021-02-29T07:49:32Z"),
value: 1024,
},
{
customer_id: "[email protected]",
orderdate: new Date("2020-10-03T13:49:44Z"),
value: 102,
},
]);

この集計チュートリアルに従う前に、新しいPHPアプリを設定する必要があります。このアプリを使用して、 MongoDBデプロイに接続し、サンプルデータをMongoDBに挿入し、集計パイプラインを実行できます。

Tip

PHPライブラリをインストールしてMongoDBに接続する方法については、 「 PHPライブラリを使い始める 」チュートリアルを参照してください。

PHPライブラリで集計を実行する方法の詳細については、 集計ガイド を参照してください。

ライブラリをインストールしたら、agg_tutorial.php というファイルを作成します。このファイルに次のコードを貼り付けて、集計チュートリアル用のアプリテンプレートを作成します。

重要

次のコードでは、コードコメントを読み取って、次のチュートリアルで変更する必要があるコードのセクションを見つけます。

変更せずにコードを実行しようとすると、接続エラーが発生します。

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

すべてのチュートリアルで、接続stringプレースホルダーを配置の接続stringに置き換える必要があります。

Tip

配置の接続文字列を見つける方法については、 「 PHPライブラリを使い始める 」チュートリアルの「 接続文字列の作成 」ステップを参照してください。

たとえば、接続stringが "mongodb+srv://mongodb-example:27017" の場合、接続stringの割り当ては次のようになります。

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

この例では、個々の製品の注文を説明するドキュメントを含む ordersコレクションを使用しています。各注文は 1 人のカスタマーのみに対応するため、集計ではカスタマーのメールアドレスが含まれる customer_idフィールドで注文ドキュメントがグループ集計れます。

ordersコレクションを作成し、サンプルデータを挿入するには、次のコードをアプリケーションに追加します。

$orders = $client->agg_tutorials_db->orders;
$orders->deleteMany([]);
$orders->insertMany(
[
[
'customer_id' => '[email protected]',
'orderdate' => new UTCDateTime(new DateTimeImmutable('2020-05-30T08:35:52')),
'value' => 231
],
[
'customer_id' => '[email protected]',
'orderdate' => new UTCDateTime(new DateTimeImmutable('2020-01-13T09:32:07')),
'value' => 99
],
[
'customer_id' => '[email protected]',
'orderdate' => new UTCDateTime(new DateTimeImmutable('2020-01-01T08:25:37')),
'value' => 63
],
[
'customer_id' => '[email protected]',
'orderdate' => new UTCDateTime(new DateTimeImmutable('2019-05-28T19:13:32')),
'value' => 2
],
[
'customer_id' => '[email protected]',
'orderdate' => new UTCDateTime(new DateTimeImmutable('2020-11-23T22:56:53')),
'value' => 187
],
[
'customer_id' => '[email protected]',
'orderdate' => new UTCDateTime(new DateTimeImmutable('2020-08-18T23:04:48')),
'value' => 4
],
[
'customer_id' => '[email protected]',
'orderdate' => new UTCDateTime(new DateTimeImmutable('2020-12-26T08:55:46')),
'value' => 4
],
[
'customer_id' => '[email protected]',
'orderdate' => new UTCDateTime(new DateTimeImmutable('2021-02-28T07:49:32')),
'value' => 1024
],
[
'customer_id' => '[email protected]',
'orderdate' => new UTCDateTime(new DateTimeImmutable('2020-10-03T13:49:44')),
'value' => 102
]
]
);

この集計チュートリアルに従う前に、新しい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に置き換える必要があります。

Tip

配置の接続文字列を見つける方法については、 「 PHPライブラリを使い始める 」チュートリアルの「 接続文字列の作成 」ステップを参照してください。

たとえば、接続stringが "mongodb+srv://mongodb-example:27017" の場合、接続stringの割り当ては次のようになります。

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

この例では、個々の製品の注文を説明するドキュメントを含む ordersコレクションを使用しています。各注文は 1 人のカスタマーのみに対応するため、集計ではカスタマーのメールアドレスが含まれる customer_idフィールドで注文ドキュメントがグループ集計れます。

ordersコレクションを作成し、サンプルデータを挿入するには、次のコードをアプリケーションに追加します。

orders_coll = agg_db["orders"]
orders_coll.delete_many({})
order_data = [
{
"customer_id": "[email protected]",
"orderdate": datetime(2020, 5, 30, 8, 35, 52),
"value": 231,
},
{
"customer_id": "[email protected]",
"orderdate": datetime(2020, 1, 13, 9, 32, 7),
"value": 99,
},
{
"customer_id": "[email protected]",
"orderdate": datetime(2020, 1, 1, 8, 25, 37),
"value": 63,
},
{
"customer_id": "[email protected]",
"orderdate": datetime(2019, 5, 28, 19, 13, 32),
"value": 2,
},
{
"customer_id": "[email protected]",
"orderdate": datetime(2020, 11, 23, 22, 56, 53),
"value": 187,
},
{
"customer_id": "[email protected]",
"orderdate": datetime(2020, 8, 18, 23, 4, 48),
"value": 4,
},
{
"customer_id": "[email protected]",
"orderdate": datetime(2020, 12, 26, 8, 55, 46),
"value": 4,
},
{
"customer_id": "[email protected]",
"orderdate": datetime(2021, 2, 28, 7, 49, 32),
"value": 1024,
},
{
"customer_id": "[email protected]",
"orderdate": datetime(2020, 10, 3, 13, 49, 44),
"value": 102,
},
]
orders_coll.insert_many(order_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に置き換える必要があります。

Tip

デプロイメントの接続文字列を見つける方法については、 Rubyをはじめるガイドの「 接続文字列の作成 」ステップを参照してください。

たとえば、接続stringが "mongodb+srv://mongodb-example:27017" の場合、接続stringの割り当ては次のようになります。

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

この例では、個々の製品の注文を説明するドキュメントを含む ordersコレクションを使用しています。各注文は 1 人のカスタマーのみに対応するため、集計ではカスタマーのメールアドレスが含まれる customer_idフィールドで注文ドキュメントがグループ集計れます。

ordersコレクションを作成し、サンプルデータを挿入するには、次のコードをアプリケーションに追加します。

orders = agg_db[:orders]
orders.delete_many({})
orders.insert_many(
[
{
customer_id: "[email protected]",
orderdate: DateTime.parse("2020-05-30T08:35:52Z"),
value: 231,
},
{
customer_id: "[email protected]",
orderdate: DateTime.parse("2020-01-13T09:32:07Z"),
value: 99,
},
{
customer_id: "[email protected]",
orderdate: DateTime.parse("2020-01-01T08:25:37Z"),
value: 63,
},
{
customer_id: "[email protected]",
orderdate: DateTime.parse("2019-05-28T19:13:32Z"),
value: 2,
},
{
customer_id: "[email protected]",
orderdate: DateTime.parse("2020-11-23T22:56:53Z"),
value: 187,
},
{
customer_id: "[email protected]",
orderdate: DateTime.parse("2020-08-18T23:04:48Z"),
value: 4,
},
{
customer_id: "[email protected]",
orderdate: DateTime.parse("2020-12-26T08:55:46Z"),
value: 4,
},
{
customer_id: "[email protected]",
orderdate: DateTime.parse("2021-02-28T07:49:32Z"),
value: 1024,
},
{
customer_id: "[email protected]",
orderdate: DateTime.parse("2020-10-03T13:49:44Z"),
value: 102,
},
]
)

この集計チュートリアルに従う前に、新しい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 { ... }
#[tokio::main]
async fn main() mongodb::error::Result<()> {
// Replace the placeholder with your connection string.
let uri = "<connection string>";
let client = Client::with_uri_str(uri).await?;
let agg_db = client.database("agg_tutorials_db");
// Get a reference to relevant collections.
// ... let some_coll: Collection<T> = agg_db.collection("...");
// ... let another_coll: Collection<T> = agg_db.collection("...");
// Delete any existing documents in collections if needed.
// ... some_coll.delete_many(doc! {}).await?;
// Insert sample data into the collection or collections.
// ... some_coll.insert_many(vec![...]).await?;
// Create an empty pipeline.
let mut pipeline = Vec::new();
// Add code to create pipeline stages.
// pipeline.push(doc! { ... });
// Run the aggregation and print the results.
let mut results = some_coll.aggregate(pipeline).await?;
while let Some(result) = results.try_next().await? {
println!("{:?}\n", result);
}
Ok(())
}

すべてのチュートリアルで、接続stringプレースホルダーを配置の接続stringに置き換える必要があります。

Tip

デプロイメントの接続文字列を見つける方法については、 Rustクイック スタートガイドの「 接続文字列の作成 」ステップを参照してください。

たとえば、接続stringが "mongodb+srv://mongodb-example:27017" の場合、接続stringの割り当ては次のようになります。

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

この例では、個々の製品の注文を説明するドキュメントを含む ordersコレクションを使用しています。各注文は 1 人のカスタマーのみに対応するため、集計ではカスタマーのメールアドレスが含まれる customer_idフィールドで注文ドキュメントがグループ集計れます。

まず、ordersコレクション内のデータをモデル化するためのRust構造体を作成します。

#[derive(Debug, Serialize, Deserialize)]
struct Order {
customer_id: String,
orderdate: DateTime,
value: i32,
}

ordersコレクションを作成し、サンプルデータを挿入するには、次のコードをアプリケーションに追加します。

let orders: Collection<Order> = agg_db.collection("orders");
orders.delete_many(doc! {}).await?;
let docs = vec![
Order {
customer_id: "[email protected]".to_string(),
orderdate: DateTime::builder().year(2020).month(5).day(30).hour(8).minute(35).second(53).build().unwrap(),
value: 231,
},
Order {
customer_id: "[email protected]".to_string(),
orderdate: DateTime::builder().year(2020).month(1).day(13).hour(9).minute(32).second(7).build().unwrap(),
value: 99,
},
Order {
customer_id: "[email protected]".to_string(),
orderdate: DateTime::builder().year(2020).month(1).day(1).hour(8).minute(25).second(37).build().unwrap(),
value: 63,
},
Order {
customer_id: "[email protected]".to_string(),
orderdate: DateTime::builder().year(2019).month(5).day(28).hour(19).minute(13).second(32).build().unwrap(),
value: 2,
},
Order {
customer_id: "[email protected]".to_string(),
orderdate: DateTime::builder().year(2020).month(11).day(23).hour(22).minute(56).second(53).build().unwrap(),
value: 187,
},
Order {
customer_id: "[email protected]".to_string(),
orderdate: DateTime::builder().year(2020).month(8).day(18).hour(23).minute(4).second(48).build().unwrap(),
value: 4,
},
Order {
customer_id: "[email protected]".to_string(),
orderdate: DateTime::builder().year(2020).month(12).day(26).hour(8).minute(55).second(46).build().unwrap(),
value: 4,
},
Order {
customer_id: "[email protected]".to_string(),
orderdate: DateTime::builder().year(2021).month(2).day(28).hour(7).minute(49).second(32).build().unwrap(),
value: 1024,
},
Order {
customer_id: "[email protected]".to_string(),
orderdate: DateTime::builder().year(2020).month(10).day(3).hour(13).minute(49).second(44).build().unwrap(),
value: 102,
},
];
orders.insert_many(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に置き換える必要があります。

Tip

配置の接続文字列を見つける方法については、 Scalaドライバーの使用開始ガイドの「 接続文字列の作成 」のステップを参照してください。

たとえば、接続stringが "mongodb+srv://mongodb-example:27017" の場合、接続stringの割り当ては次のようになります。

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

この例では、個々の製品の注文を説明するドキュメントを含む ordersコレクションを使用しています。各注文は 1 人のカスタマーのみに対応するため、集計ではカスタマーのメールアドレスが含まれる customer_idフィールドで注文ドキュメントがグループ集計れます。

ordersコレクションを作成し、サンプルデータを挿入するには、次のコードをアプリケーションに追加します。

val orders = aggDB.getCollection("orders")
orders.deleteMany(Filters.empty()).subscribe(
_ => {},
e => println("Error: " + e.getMessage),
)
val dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
orders.insertMany(Seq(
Document("customer_id" -> "[email protected]",
"orderdate" -> dateFormat.parse("2020-05-30T08:35:52"),
"value" -> 231),
Document("customer_id" -> "[email protected]",
"orderdate" -> dateFormat.parse("2020-01-13T09:32:07"),
"value" -> 99),
Document("customer_id" -> "[email protected]",
"orderdate" -> dateFormat.parse("2020-01-01T08:25:37"),
"value" -> 63),
Document("customer_id" -> "[email protected]",
"orderdate" -> dateFormat.parse("2019-05-28T19:13:32"),
"value" -> 2),
Document("customer_id" -> "[email protected]",
"orderdate" -> dateFormat.parse("2020-11-23T22:56:53"),
"value" -> 187),
Document("customer_id" -> "[email protected]",
"orderdate" -> dateFormat.parse("2020-08-18T23:04:48"),
"value" -> 4),
Document("customer_id" -> "[email protected]",
"orderdate" -> dateFormat.parse("2020-12-26T08:55:46"),
"value" -> 4),
Document("customer_id" -> "[email protected]",
"orderdate" -> dateFormat.parse("2021-02-28T07:49:32"),
"value" -> 1024),
Document("customer_id" -> "[email protected]",
"orderdate" -> dateFormat.parse("2020-10-03T13:49:44"),
"value" -> 102)
)).subscribe(
_ => {},
e => println("Error: " + e.getMessage),
)

次の手順は、集計パイプラインを作成して実行し、ドキュメントをグループ化し、新しいフィールドを計算する方法を示しています。

1
db.orders.aggregate( [
// Stage 1: Match orders in 2020
{ $match: {
orderdate: {
$gte: new Date("2020-01-01T00:00:00Z"),
$lt: new Date("2021-01-01T00:00:00Z"),
}
} },
// Stage 2: Sort orders by date
{ $sort: { orderdate: 1 } },
// Stage 3: Group orders by email address
{ $group: {
_id: "$customer_id",
first_purchase_date: { $first: "$orderdate" },
total_value: { $sum: "$value" },
total_orders: { $sum: 1 },
orders: { $push:
{
orderdate: "$orderdate",
value: "$value"
}
}
} },
// Stage 4: Sort orders by first order date
{ $sort: { first_purchase_date: 1 } },
// Stage 5: Display the customers' email addresses
{ $set: { customer_id: "$_id" } },
// Stage 6: Remove unneeded fields
{ $unset: ["_id"] }
] )
2

この集計により、2020 からのカスタマーの注文の次の概要が返されます。結果ドキュメントには、特定のカスタマーが行ったすべての注文の詳細が、カスタマーのメールアドレス別にグループ化されて含まれます。

{
first_purchase_date: ISODate("2020-01-01T08:25:37.000Z"),
total_value: 63,
total_orders: 1,
orders: [ { orderdate: ISODate("2020-01-01T08:25:37.000Z"), value: 63 } ],
customer_id: '[email protected]'
}
{
first_purchase_date: ISODate("2020-01-13T09:32:07.000Z"),
total_value: 436,
total_orders: 4,
orders: [
{ orderdate: ISODate("2020-01-13T09:32:07.000Z"), value: 99 },
{ orderdate: ISODate("2020-05-30T08:35:52.000Z"), value: 231 },
{ orderdate: ISODate("2020-10-03T13:49:44.000Z"), value: 102 },
{ orderdate: ISODate("2020-12-26T08:55:46.000Z"), value: 4 }
],
customer_id: '[email protected]'
}
{
first_purchase_date: ISODate("2020-08-18T23:04:48.000Z"),
total_value: 191,
total_orders: 2,
orders: [
{ orderdate: ISODate("2020-08-18T23:04:48.000Z"), value: 4 },
{ orderdate: ISODate("2020-11-23T22:56:53.000Z"), value: 187 }
],
customer_id: '[email protected]'
}
1

まず、$match の注文に一致する2020 ステージを追加します。

"{", "$match", "{",
"orderdate", "{",
"$gte", BCON_DATE_TIME(1577836800000UL), // Represents 2020-01-01T00:00:00Z
"$lt", BCON_DATE_TIME(1609459200000UL), // Represents 2021-01-01T00:00:00Z
"}",
"}", "}",
2

次に、$sort ステージを追加して、orderdate 2020フィールドに昇順の並べ替えを設定し、次のステージで各カスタマー向けの最も近い の購入を取得します。

"{", "$sort", "{", "orderdate", BCON_INT32(1), "}", "}",
3

$groupフィールドの値で注文ドキュメントを収集するために、customer_id ステージを追加します。このステージでは、結果ドキュメントに次のフィールドを作成する集計操作を追加します。

  • first_purchase_date: カスタマーの最初の購入日

  • total_value: すべてのカスタマーの売上合計値

  • total_orders: カスタマーの購入合計数

  • orders: 各購入の日付と金額を含む、すべてのカスタマーの購入のリスト

"{", "$group", "{",
"_id", BCON_UTF8("$customer_id"),
"first_purchase_date", "{", "$first", BCON_UTF8("$orderdate"), "}",
"total_value", "{", "$sum", BCON_UTF8("$value"), "}",
"total_orders", "{", "$sum", BCON_INT32(1), "}",
"orders", "{", "$push", "{",
"orderdate", BCON_UTF8("$orderdate"),
"value", BCON_UTF8("$value"),
"}", "}",
"}", "}",
4

次に、別の$sort ステージを追加して、first_purchase_date フィールドで昇順の並べ替えを設定します。

"{", "$sort", "{", "first_purchase_date", BCON_INT32(1), "}", "}",
5

$setステージを追加して、 ステージ中に設定されたcustomer_id フィールドの値から フィールドを再作成します。_id$group

"{", "$set", "{", "customer_id", BCON_UTF8("$_id"), "}", "}",
6

最後に、$unset ステージを追加します。$unset ステージでは、結果ドキュメントから フィールドが削除されます。_id

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

次のコードをアプリケーションの末尾に追加して、 ordersコレクションで集計を実行します。

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

クリーンアップ ステートメントに次の行を追加して、コレクションリソースをクリーンアップするようにします。

mongoc_collection_destroy(orders);

最後に、 シェルで次のコマンドを実行して実行可能ファイルを生成および実行します。

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

Tip

上記のコマンドを 1 回の呼び出しで実行中て接続エラーが発生した場合は、個別に実行できます。

8

この集計により、2020 年からのカスタマーの注文に関する次の概要が返されます。

{ "first_purchase_date" : { "$date" : { "$numberLong" : "1577865937000" } }, "total_value" : { "$numberInt" : "63" }, "total_orders" : { "$numberInt" : "1" }, "orders" : [ { "orderdate" : { "$date" : { "$numberLong" : "1577865937000" } }, "value" : { "$numberInt" : "63" } } ], "customer_id" : "[email protected]" }
{ "first_purchase_date" : { "$date" : { "$numberLong" : "1578904327000" } }, "total_value" : { "$numberInt" : "436" }, "total_orders" : { "$numberInt" : "4" }, "orders" : [ { "orderdate" : { "$date" : { "$numberLong" : "1578904327000" } }, "value" : { "$numberInt" : "99" } }, { "orderdate" : { "$date" : { "$numberLong" : "1590825352000" } }, "value" : { "$numberInt" : "231" } }, { "orderdate" : { "$date" : { "$numberLong" : "1601722184000" } }, "value" : { "$numberInt" : "102" } }, { "orderdate" : { "$date" : { "$numberLong" : "1608963346000" } }, "value" : { "$numberInt" : "4" } } ], "customer_id" : "[email protected]" }
{ "first_purchase_date" : { "$date" : { "$numberLong" : "1597793088000" } }, "total_value" : { "$numberInt" : "191" }, "total_orders" : { "$numberInt" : "2" }, "orders" : [ { "orderdate" : { "$date" : { "$numberLong" : "1597793088000" } }, "value" : { "$numberInt" : "4" } }, { "orderdate" : { "$date" : { "$numberLong" : "1606171013000" } }, "value" : { "$numberInt" : "187" } } ], "customer_id" : "[email protected]" }

結果ドキュメントには、特定のカスタマーからのすべての注文の詳細が、カスタマーのメールアドレス別にグループ化されて含まれます。

1

まず、$match の注文に一致する2020 ステージを追加します。

pipeline.match(bsoncxx::from_json(R"({
"orderdate": {
"$gte": {"$date": 1577836800},
"$lt": {"$date": 1609459200000}
}
})"));
2

次に、$sort ステージを追加して、orderdate 2020フィールドに昇順の並べ替えを設定し、次のステージで各カスタマー向けの最も近い の購入を取得します。

pipeline.sort(bsoncxx::from_json(R"({
"orderdate": 1
})"));
3

$groupフィールドの値で注文ドキュメントを収集するために、customer_id ステージを追加します。このステージでは、結果ドキュメントに次のフィールドを作成する集計操作を追加します。

  • first_purchase_date: カスタマーの最初の購入日

  • total_value: すべてのカスタマーの売上合計値

  • total_orders: カスタマーの購入合計数

  • orders: 各購入の日付と金額を含む、すべてのカスタマーの購入のリスト

pipeline.group(bsoncxx::from_json(R"({
"_id": "$customer_id",
"first_purchase_date": {"$first": "$orderdate"},
"total_value": {"$sum": "$value"},
"total_orders": {"$sum": 1},
"orders": {"$push": {
"orderdate": "$orderdate",
"value": "$value"
}}
})"));
4

次に、別の$sort ステージを追加して、first_purchase_date フィールドで昇順の並べ替えを設定します。

pipeline.sort(bsoncxx::from_json(R"({
"first_purchase_date": 1
})"));
5

$addFields$setステージのエイリアスである ステージを追加して、 ステージ中に設定されたcustomer_id フィールドの値から フィールドを再作成します。_id$group

pipeline.add_fields(bsoncxx::from_json(R"({
"customer_id": "$_id"
})"));
6

最後に、$unset ステージを追加します。$unset ステージでは、結果ドキュメントから フィールドが削除されます。_id

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

次のコードをアプリケーションの末尾に追加して、 ordersコレクションで集計を実行します。

auto cursor = orders.aggregate(pipeline);

最後に、shell で次のコマンドを実行してアプリケーションを起動します。

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

この集計により、2020 年からのカスタマーの注文に関する次の概要が返されます。

{ "first_purchase_date" : { "$date" : "1970-01-19T06:17:41.137Z" }, "total_value" : 63,
"total_orders" : 1, "orders" : [ { "orderdate" : { "$date" : "1970-01-19T06:17:41.137Z" },
"value" : 63 } ], "customer_id" : "[email protected]" }
{ "first_purchase_date" : { "$date" : "1970-01-19T06:35:01.927Z" }, "total_value" : 436,
"total_orders" : 4, "orders" : [ { "orderdate" : { "$date" : "1970-01-19T06:35:01.927Z" },
"value" : 99 }, { "orderdate" : { "$date" : "2020-05-30T06:55:52Z" }, "value" : 231 },
{ "orderdate" : { "$date" : "2020-10-03T10:49:44Z" }, "value" : 102 }, { "orderdate" :
{ "$date" : "2020-12-26T08:55:46Z" }, "value" : 4 } ], "customer_id" : "[email protected]" }
{ "first_purchase_date" : { "$date" : "1970-01-19T11:49:54.288Z" }, "total_value" : 1215,
"total_orders" : 3, "orders" : [ { "orderdate" : { "$date" : "1970-01-19T11:49:54.288Z" },
"value" : 4 }, { "orderdate" : { "$date" : "1970-01-19T14:09:32.213Z" }, "value" : 187 },
{ "orderdate" : { "$date" : "1970-01-19T16:29:30.572Z" }, "value" : 1024 } ], "customer_id" : "[email protected]" }

結果ドキュメントには、特定のカスタマーからのすべての注文の詳細が、カスタマーのメールアドレス別にグループ化されて含まれます。

1

まず、 コレクションで集計を開始し、orders $matchの注文に一致する2020 ステージをチェーンします。

var results = orders.Aggregate()
.Match(o => o.OrderDate >= DateTime.Parse("2020-01-01T00:00:00Z") &&
o.OrderDate < DateTime.Parse("2021-01-01T00:00:00Z"))
2

次に、$sort ステージを追加して、OrderDate 2020フィールドに昇順の並べ替えを設定し、次のステージで各カスタマー向けの最も近い の購入を取得します。

.SortBy(o => o.OrderDate)
3

$groupフィールドの値で注文ドキュメントを収集するために、CustomerId ステージを追加します。このステージでは、結果ドキュメントに次のフィールドを作成する集計操作を追加します。

  • CustomerId: カスタマーのメールアドレス(グループ化キー)

  • FirstPurchaseDate: カスタマーの最初の購入日

  • TotalValue: すべてのカスタマーの売上合計値

  • TotalOrders: カスタマーの購入合計数

  • Orders: 各購入の日付と金額を含む、すべてのカスタマーの購入のリスト

.Group(
o => o.CustomerId,
g => new
{
CustomerId = g.Key,
FirstPurchaseDate = g.First().OrderDate,
TotalValue = g.Sum(i => i.Value),
TotalOrders = g.Count(),
Orders = g.Select(i => new { i.OrderDate, i.Value }).ToList()
}
)
4

次に、別の$sort ステージを追加して、FirstPurchaseDate フィールドで昇順の並べ替えを設定します。

.SortBy(c => c.FirstPurchaseDate)
.As<BsonDocument>();

上記のコードでは、出力用に出力ドキュメントも BsonDocument インスタンスに変換されています。

5

最後に、IDE でアプリケーションを実行し、結果を調べます。

この集計により、2020 年からのカスタマーの注文に関する次の概要が返されます。

{ "CustomerId" : "[email protected]", "FirstPurchaseDate" : { "$date" : "2020-01-01T08:25:37Z" }, "TotalValue" : 63, "TotalOrders" : 1, "Orders" : [{ "OrderDate" : { "$date" : "2020-01-01T08:25:37Z" }, "Value" : 63 }] }
{ "CustomerId" : "[email protected]", "FirstPurchaseDate" : { "$date" : "2020-01-13T09:32:07Z" }, "TotalValue" : 436, "TotalOrders" : 4, "Orders" : [{ "OrderDate" : { "$date" : "2020-01-13T09:32:07Z" }, "Value" : 99 }, { "OrderDate" : { "$date" : "2020-05-30T08:35:52Z" }, "Value" : 231 }, { "OrderDate" : { "$date" : "2020-10-03T13:49:44Z" }, "Value" : 102 }, { "OrderDate" : { "$date" : "2020-12-26T08:55:46Z" }, "Value" : 4 }] }
{ "CustomerId" : "[email protected]", "FirstPurchaseDate" : { "$date" : "2020-08-18T23:04:48Z" }, "TotalValue" : 191, "TotalOrders" : 2, "Orders" : [{ "OrderDate" : { "$date" : "2020-08-18T23:04:48Z" }, "Value" : 4 }, { "OrderDate" : { "$date" : "2020-11-23T22:56:53Z" }, "Value" : 187 }] }

結果ドキュメントには、特定のカスタマーからのすべての注文の詳細が、カスタマーのメールアドレス別にグループ化されて含まれます。

1

まず、$match の注文に一致する2020 ステージを追加します。

matchStage := 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)},
}},
}}}
2

次に、$sort ステージを追加して、orderdate 2020フィールドに昇順の並べ替えを設定し、次のステージで各カスタマー向けの最も近い の購入を取得します。

sortStage1 := bson.D{{Key: "$sort", Value: bson.D{
{Key: "orderdate", Value: 1},
}}}
3

$groupフィールドの値で注文ドキュメントを収集するために、customer_id ステージを追加します。このステージでは、結果ドキュメントに次のフィールドを作成する集計操作を追加します。

  • first_purchase_date: カスタマーの最初の購入日

  • total_value: すべてのカスタマーの売上合計値

  • total_orders: カスタマーの購入合計数

  • orders: 各購入の日付と金額を含む、すべてのカスタマーの購入のリスト

groupStage := bson.D{{Key: "$group", Value: bson.D{
{Key: "_id", Value: "$customer_id"},
{Key: "first_purchase_date", Value: bson.D{{Key: "$first", Value: "$orderdate"}}},
{Key: "total_value", Value: bson.D{{Key: "$sum", Value: "$value"}}},
{Key: "total_orders", Value: bson.D{{Key: "$sum", Value: 1}}},
{Key: "orders", Value: bson.D{{Key: "$push", Value: bson.D{
{Key: "orderdate", Value: "$orderdate"},
{Key: "value", Value: "$value"},
}}}},
}}}
4

次に、別の$sort ステージを追加して、first_purchase_date フィールドで昇順の並べ替えを設定します。

sortStage2 := bson.D{{Key: "$sort", Value: bson.D{
{Key: "first_purchase_date", Value: 1},
}}}
5

$setステージを追加して、 ステージ中に設定されたcustomer_id フィールドの値から フィールドを再作成します。_id$group

setStage := bson.D{{Key: "$set", Value: bson.D{
{Key: "customer_id", Value: "$_id"},
}}}
6

最後に、$unset ステージを追加します。$unset ステージでは、結果ドキュメントから フィールドが削除されます。_id

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

次のコードをアプリケーションの末尾に追加して、 ordersコレクションで集計を実行します。

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

最後に、shell で次のコマンドを実行してアプリケーションを起動します。

go run agg_tutorial.go
8

この集計により、2020 年からのカスタマーの注文に関する次の概要が返されます。

{"first_purchase_date":{"$date":"2020-01-01T08:25:37Z"},"total_value":63,"total_orders":1,"orders":[{"orderdate":{"$date":"2020-01-01T08:25:37Z"},"value":63}],"customer_id":"[email protected]"}
{"first_purchase_date":{"$date":"2020-01-13T09:32:07Z"},"total_value":436,"total_orders":4,"orders":[{"orderdate":{"$date":"2020-01-13T09:32:07Z"},"value":99},{"orderdate":{"$date":"2020-05-30T08:35:53Z"},"value":231},{"orderdate":{"$date":"2020-10-03T13:49:44Z"},"value":102},{"orderdate":{"$date":"2020-12-26T08:55:46Z"},"value":4}],"customer_id":"[email protected]"}
{"first_purchase_date":{"$date":"2020-08-18T23:04:48Z"},"total_value":191,"total_orders":2,"orders":[{"orderdate":{"$date":"2020-08-18T23:04:48Z"},"value":4},{"orderdate":{"$date":"2020-11-23T22:56:53Z"},"value":187}],"customer_id":"[email protected]"}

結果ドキュメントには、特定のカスタマーからのすべての注文の詳細が、カスタマーのメールアドレス別にグループ化されて含まれます。

1

まず、$match の注文に一致する2020 ステージを追加します。

pipeline.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"))
)));
2

次に、$sort ステージを追加して、orderdate 2020フィールドに昇順の並べ替えを設定し、次のステージで各カスタマー向けの最も近い の購入を取得します。

pipeline.add(Aggregates.sort(Sorts.ascending("orderdate")));
3

$groupフィールドの値で注文ドキュメントを収集するために、customer_id ステージを追加します。このステージでは、結果ドキュメントに次のフィールドを作成する集計操作を追加します。

  • first_purchase_date: カスタマーの最初の購入日

  • total_value: すべてのカスタマーの売上合計値

  • total_orders: カスタマーの購入合計数

  • orders: 各購入の日付と金額を含む、すべてのカスタマーの購入のリスト

pipeline.add(Aggregates.group(
"$customer_id",
Accumulators.first("first_purchase_date", "$orderdate"),
Accumulators.sum("total_value", "$value"),
Accumulators.sum("total_orders", 1),
Accumulators.push("orders",
new Document("orderdate", "$orderdate")
.append("value", "$value")
)
));
4

次に、別の$sort ステージを追加して、first_purchase_date フィールドで昇順の並べ替えを設定します。

pipeline.add(Aggregates.sort(Sorts.ascending("first_purchase_date")));
5

$setステージを追加して、 ステージ中に設定されたcustomer_id フィールドの値から フィールドを再作成します。_id$group

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

最後に、$unset ステージを追加します。$unset ステージでは、結果ドキュメントから フィールドが削除されます。_id

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

次のコードをアプリケーションの末尾に追加して、 ordersコレクションで集計を実行します。

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

最後に、アプリケーションを IDE で実行します。

8

この集計により、2020 年からのカスタマーの注文に関する次の概要が返されます。

{"first_purchase_date": {"$date": "2020-01-01T08:25:37Z"}, "total_value": 63, "total_orders": 1, "orders": [{"orderdate": {"$date": "2020-01-01T08:25:37Z"}, "value": 63}], "customer_id": "[email protected]"}
{"first_purchase_date": {"$date": "2020-01-13T09:32:07Z"}, "total_value": 436, "total_orders": 4, "orders": [{"orderdate": {"$date": "2020-01-13T09:32:07Z"}, "value": 99}, {"orderdate": {"$date": "2020-05-30T08:35:52Z"}, "value": 231}, {"orderdate": {"$date": "2020-10-03T13:49:44Z"}, "value": 102}, {"orderdate": {"$date": "2020-12-26T08:55:46Z"}, "value": 4}], "customer_id": "[email protected]"}
{"first_purchase_date": {"$date": "2020-08-18T23:04:48Z"}, "total_value": 191, "total_orders": 2, "orders": [{"orderdate": {"$date": "2020-08-18T23:04:48Z"}, "value": 4}, {"orderdate": {"$date": "2020-11-23T22:56:53Z"}, "value": 187}], "customer_id": "[email protected]"}

結果ドキュメントには、特定のカスタマーからのすべての注文の詳細が、カスタマーのメールアドレス別にグループ化されて含まれます。

1

まず、$match の注文に一致する2020 ステージを追加します。

pipeline.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())
)
)
)
2

次に、$sort ステージを追加して、orderDate 2020フィールドに昇順の並べ替えを設定し、次のステージで各カスタマー向けの最も近い の購入を取得します。

pipeline.add(Aggregates.sort(Sorts.ascending(Order::orderDate.name)))
3

$groupフィールドの値で注文ドキュメントを収集するために、customer_id ステージを追加します。このステージでは、結果ドキュメントに次のフィールドを作成する集計操作を追加します。

  • first_purchase_date: カスタマーの最初の購入日

  • total_value: すべてのカスタマーの売上合計値

  • total_orders: カスタマーの購入合計数

  • orders: 各購入の日付と金額を含む、すべてのカスタマーの購入のリスト

pipeline.add(
Aggregates.group(
"\$${Order::customerID.name}",
Accumulators.first("first_purchase_date", "\$${Order::orderDate.name}"),
Accumulators.sum("total_value", "\$${Order::value.name}"),
Accumulators.sum("total_orders", 1),
Accumulators.push(
"orders",
Document("orderdate", "\$${Order::orderDate.name}")
.append("value", "\$${Order::value.name}")
)
)
)
4

次に、別の$sort ステージを追加して、first_purchase_date フィールドで昇順の並べ替えを設定します。

pipeline.add(Aggregates.sort(Sorts.ascending("first_purchase_date")))
5

$setステージを追加して、 ステージ中に設定されたcustomer_id フィールドの値から フィールドを再作成します。_id$group

pipeline.add(Aggregates.set(Field("customer_id", "\$_id")))
6

最後に、$unset ステージを追加します。$unset ステージでは、結果ドキュメントから フィールドが削除されます。_id

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

次のコードをアプリケーションの末尾に追加して、 ordersコレクションで集計を実行します。

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

最後に、アプリケーションを IDE で実行します。

8

この集計により、2020 年からのカスタマーの注文に関する次の概要が返されます。

Document{{first_purchase_date=Wed Jan 01 03:25:37 EST 2020, total_value=63, total_orders=1, orders=[Document{{orderdate=Wed Jan 01 03:25:37 EST 2020, value=63}}], [email protected]}}
Document{{first_purchase_date=Mon Jan 13 04:32:07 EST 2020, total_value=436, total_orders=4, orders=[Document{{orderdate=Mon Jan 13 04:32:07 EST 2020, value=99}}, Document{{orderdate=Sat May 30 04:35:52 EDT 2020, value=231}}, Document{{orderdate=Sat Oct 03 09:49:44 EDT 2020, value=102}}, Document{{orderdate=Sat Dec 26 03:55:46 EST 2020, value=4}}], [email protected]}}
Document{{first_purchase_date=Tue Aug 18 19:04:48 EDT 2020, total_value=191, total_orders=2, orders=[Document{{orderdate=Tue Aug 18 19:04:48 EDT 2020, value=4}}, Document{{orderdate=Mon Nov 23 17:56:53 EST 2020, value=187}}], [email protected]}}

結果ドキュメントには、特定のカスタマーからのすべての注文の詳細が、カスタマーのメールアドレス別にグループ化されて含まれます。

1

まず、$match の注文に一致する2020 ステージを追加します。

pipeline.push({
$match: {
orderdate: {
$gte: new Date("2020-01-01T00:00:00Z"),
$lt: new Date("2021-01-01T00:00:00Z"),
},
},
});
2

次に、$sort ステージを追加して、orderdate 2020フィールドに昇順の並べ替えを設定し、次のステージで各カスタマー向けの最も近い の購入を取得します。

pipeline.push({
$sort: {
orderdate: 1,
},
});
3

$groupcustomer_idステージを追加して、 フィールドの値で注文をグループ化します。このステージでは、結果ドキュメントに次のフィールドを作成する集計操作を追加します。

  • first_purchase_date: カスタマーの最初の購入日

  • total_value: すべてのカスタマーの売上合計値

  • total_orders: カスタマーの購入合計数

  • orders: 各購入の日付と金額を含む、すべてのカスタマーの購入のリスト

pipeline.push({
$group: {
_id: "$customer_id",
first_purchase_date: { $first: "$orderdate" },
total_value: { $sum: "$value" },
total_orders: { $sum: 1 },
orders: {
$push: {
orderdate: "$orderdate",
value: "$value",
},
},
},
});
4

次に、別の$sort ステージを追加して、first_purchase_date フィールドで昇順の並べ替えを設定します。

pipeline.push({
$sort: {
first_purchase_date: 1,
},
});
5

$setステージを追加して、 ステージ中に設定されたcustomer_id フィールドの値から フィールドを再作成します。_id$group

pipeline.push({
$set: {
customer_id: "$_id",
},
});
6

最後に、$unset ステージを追加します。$unset ステージでは、結果ドキュメントから フィールドが削除されます。_id

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

次のコードをアプリケーションの末尾に追加して、 ordersコレクションで集計を実行します。

const aggregationResult = await orders.aggregate(pipeline);

最後に、shell で次のコマンドを実行してアプリケーションを起動します。

node agg_tutorial.js
8

この集計により、2020 年からのカスタマーの注文に関する次の概要が返されます。

{
first_purchase_date: 2020-01-01T08:25:37.000Z,
total_value: 63,
total_orders: 1,
orders: [ { orderdate: 2020-01-01T08:25:37.000Z, value: 63 } ],
customer_id: '[email protected]'
}
{
first_purchase_date: 2020-01-13T09:32:07.000Z,
total_value: 436,
total_orders: 4,
orders: [
{ orderdate: 2020-01-13T09:32:07.000Z, value: 99 },
{ orderdate: 2020-05-30T08:35:52.000Z, value: 231 },
{ orderdate: 2020-10-03T13:49:44.000Z, value: 102 },
{ orderdate: 2020-12-26T08:55:46.000Z, value: 4 }
],
customer_id: '[email protected]'
}
{
first_purchase_date: 2020-08-18T23:04:48.000Z,
total_value: 191,
total_orders: 2,
orders: [
{ orderdate: 2020-08-18T23:04:48.000Z, value: 4 },
{ orderdate: 2020-11-23T22:56:53.000Z, value: 187 }
],
customer_id: '[email protected]'
}

結果ドキュメントには、特定のカスタマーからのすべての注文の詳細が、カスタマーのメールアドレス別にグループ化されて含まれます。

1

Pipeline$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'))),
]
),
2

次に、$sort ステージを追加して、orderdate 2020フィールドに昇順の並べ替えを設定し、次のステージで各カスタマー向けの最も近い の購入を取得します。

Stage::sort(orderdate: Sort::Asc),
3

Pipeline$groupcustomer_idインスタンスの外部に、ファクトリー関数で ステージを作成し、 フィールドの値で注文ドキュメントを収集します。このステージでは、結果ドキュメントに次のフィールドを作成する集計操作を追加します。

  • first_purchase_date: カスタマーの最初の購入日

  • total_value: すべてのカスタマーの売上合計値

  • total_orders: カスタマーの購入合計数

  • orders: 各購入の日付と金額を含む、すべてのカスタマーの購入のリスト

function groupByCustomerStage()
{
return Stage::group(
_id: Expression::stringFieldPath('customer_id'),
first_purchase_date: Accumulator::first(
Expression::arrayFieldPath('orderdate')
),
total_value: Accumulator::sum(
Expression::numberFieldPath('value'),
),
total_orders: Accumulator::sum(1),
orders: Accumulator::push(
object(
orderdate: Expression::dateFieldPath('orderdate'),
value: Expression::numberFieldPath('value'),
),
),
);
}

次に、Pipelineインスタンスで、groupByCustomerStage() 関数を呼び出します。

groupByCustomerStage(),
4

次に、別の$sort ステージを作成して、first_purchase_date フィールドで昇順の並べ替えを設定します。

Stage::sort(first_purchase_date: Sort::Asc),
5

$setステージを追加して、 ステージ中に設定されたcustomer_id フィールドの値から フィールドを再作成します。_id$group

Stage::set(customer_id: Expression::stringFieldPath('_id')),
6

最後に、$unset ステージを追加します。$unset ステージでは、結果ドキュメントから フィールドが削除されます。_id

Stage::unset('_id')
7

次のコードをアプリケーションの末尾に追加して、 ordersコレクションで集計を実行します。

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

最後に、shell で次のコマンドを実行してアプリケーションを起動します。

php agg_tutorial.php
8

この集計により、2020 年からのカスタマーの注文に関する次の概要が返されます。

{
"first_purchase_date": {
"$date": {
"$numberLong": "1577867137000"
}
},
"total_value": 63,
"total_orders": 1,
"orders": [
{
"orderdate": {
"$date": {
"$numberLong": "1577867137000"
}
},
"value": 63
}
],
"customer_id": "[email protected]"
}
{
"first_purchase_date": {
"$date": {
"$numberLong": "1578907927000"
}
},
"total_value": 436,
"total_orders": 4,
"orders": [
{
"orderdate": {
"$date": {
"$numberLong": "1578907927000"
}
},
"value": 99
},
{
"orderdate": {
"$date": {
"$numberLong": "1590827752000"
}
},
"value": 231
},
{
"orderdate": {
"$date": {
"$numberLong": "1601732984000"
}
},
"value": 102
},
{
"orderdate": {
"$date": {
"$numberLong": "1608972946000"
}
},
"value": 4
}
],
"customer_id": "[email protected]"
}
{
"first_purchase_date": {
"$date": {
"$numberLong": "1597791888000"
}
},
"total_value": 191,
"total_orders": 2,
"orders": [
{
"orderdate": {
"$date": {
"$numberLong": "1597791888000"
}
},
"value": 4
},
{
"orderdate": {
"$date": {
"$numberLong": "1606172213000"
}
},
"value": 187
}
],
"customer_id": "[email protected]"
}

結果ドキュメントには、特定のカスタマーからのすべての注文の詳細が、カスタマーのメールアドレス別にグループ化されて含まれます。

1

Pipeline$matchインスタンスに、 の注文に一致する2020 ステージを追加します。

pipeline.append(
{
"$match": {
"orderdate": {
"$gte": datetime(2020, 1, 1, 0, 0, 0),
"$lt": datetime(2021, 1, 1, 0, 0, 0),
}
}
}
)
2

次に、$sort ステージを追加して、orderdate 2020フィールドに昇順の並べ替えを設定し、次のステージで各カスタマー向けの最も近い の購入を取得します。

pipeline.append({"$sort": {"orderdate": 1}})
3

$groupcustomer_idステージを追加して、 フィールドの値で注文をグループ化します。このステージでは、結果ドキュメントに次のフィールドを作成する集計操作を追加します。

  • first_purchase_date: カスタマーの最初の購入日

  • total_value: すべてのカスタマーの売上合計値

  • total_orders: カスタマーの購入合計数

  • orders: 各購入の日付と金額を含む、すべてのカスタマーの購入のリスト

pipeline.append(
{
"$group": {
"_id": "$customer_id",
"first_purchase_date": {"$first": "$orderdate"},
"total_value": {"$sum": "$value"},
"total_orders": {"$sum": 1},
"orders": {"$push": {"orderdate": "$orderdate", "value": "$value"}},
}
}
)
4

次に、別の$sort ステージを作成して、first_purchase_date フィールドで昇順の並べ替えを設定します。

pipeline.append({"$sort": {"first_purchase_date": 1}})
5

$setステージを追加して、 ステージ中に設定されたcustomer_id フィールドの値から フィールドを再作成します。_id$group

pipeline.append({"$set": {"customer_id": "$_id"}})
6

最後に、$unset ステージを追加します。$unset ステージでは、結果ドキュメントから フィールドが削除されます。_id

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

次のコードをアプリケーションの末尾に追加して、 ordersコレクションで集計を実行します。

aggregation_result = orders_coll.aggregate(pipeline)

最後に、shell で次のコマンドを実行してアプリケーションを起動します。

python3 agg_tutorial.py
8

この集計により、2020 年からのカスタマーの注文に関する次の概要が返されます。

{'first_purchase_date': datetime.datetime(2020, 1, 1, 8, 25, 37), 'total_value': 63, 'total_orders': 1, 'orders': [{'orderdate': datetime.datetime(2020, 1, 1, 8, 25, 37), 'value': 63}], 'customer_id': '[email protected]'}
{'first_purchase_date': datetime.datetime(2020, 1, 13, 9, 32, 7), 'total_value': 436, 'total_orders': 4, 'orders': [{'orderdate': datetime.datetime(2020, 1, 13, 9, 32, 7), 'value': 99}, {'orderdate': datetime.datetime(2020, 5, 30, 8, 35, 52), 'value': 231}, {'orderdate': datetime.datetime(2020, 10, 3, 13, 49, 44), 'value': 102}, {'orderdate': datetime.datetime(2020, 12, 26, 8, 55, 46), 'value': 4}], 'customer_id': '[email protected]'}
{'first_purchase_date': datetime.datetime(2020, 8, 18, 23, 4, 48), 'total_value': 191, 'total_orders': 2, 'orders': [{'orderdate': datetime.datetime(2020, 8, 18, 23, 4, 48), 'value': 4}, {'orderdate': datetime.datetime(2020, 11, 23, 22, 56, 53), 'value': 187}], 'customer_id': '[email protected]'}

結果ドキュメントには、特定のカスタマーからのすべての注文の詳細が、カスタマーのメールアドレス別にグループ化されて含まれます。

1

まず、$match の注文に一致する2020 ステージを追加します。

{
"$match": {
orderdate: {
"$gte": DateTime.parse("2020-01-01T00:00:00Z"),
"$lt": DateTime.parse("2021-01-01T00:00:00Z"),
},
},
},
2

次に、$sort ステージを追加して、orderdate 2020フィールドに昇順の並べ替えを設定し、次のステージで各カスタマー向けの最も近い の購入を取得します。

{
"$sort": {
orderdate: 1,
},
},
3

$groupフィールドの値で注文ドキュメントを収集するために、customer_id ステージを追加します。このステージでは、結果ドキュメントに次のフィールドを作成する集計操作を追加します。

  • first_purchase_date: カスタマーの最初の購入日

  • total_value: すべてのカスタマーの売上合計値

  • total_orders: カスタマーの購入合計数

  • orders: 各購入の日付と金額を含む、すべてのカスタマーの購入のリスト

{
"$group": {
_id: "$customer_id",
first_purchase_date: { "$first": "$orderdate" },
total_value: { "$sum": "$value" },
total_orders: { "$sum": 1 },
orders: { "$push": {
orderdate: "$orderdate",
value: "$value",
} },
},
},
4

次に、別の$sort ステージを追加して、first_purchase_date フィールドで昇順の並べ替えを設定します。

{
"$sort": {
first_purchase_date: 1,
},
},
5

$setステージを追加して、 ステージ中に設定されたcustomer_id フィールドの値から フィールドを再作成します。_id$group

{
"$set": {
customer_id: "$_id",
},
},
6

最後に、$unset ステージを追加します。$unset ステージでは、結果ドキュメントから フィールドが削除されます。_id

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

次のコードをアプリケーションの末尾に追加して、 ordersコレクションで集計を実行します。

aggregation_result = orders.aggregate(pipeline)

最後に、shell で次のコマンドを実行してアプリケーションを起動します。

ruby agg_tutorial.rb
8

この集計により、2020 年からのカスタマーの注文に関する次の概要が返されます。

{"first_purchase_date"=>2020-01-01 08:25:37 UTC, "total_value"=>63, "total_orders"=>1, "orders"=>[{"orderdate"=>2020-01-01 08:25:37 UTC, "value"=>63}], "customer_id"=>"[email protected]"}
{"first_purchase_date"=>2020-01-13 09:32:07 UTC, "total_value"=>436, "total_orders"=>4, "orders"=>[{"orderdate"=>2020-01-13 09:32:07 UTC, "value"=>99}, {"orderdate"=>2020-05-30 08:35:52 UTC, "value"=>231}, {"orderdate"=>2020-10-03 13:49:44 UTC, "value"=>102}, {"orderdate"=>2020-12-26 08:55:46 UTC, "value"=>4}], "customer_id"=>"[email protected]"}
{"first_purchase_date"=>2020-08-18 23:04:48 UTC, "total_value"=>191, "total_orders"=>2, "orders"=>[{"orderdate"=>2020-08-18 23:04:48 UTC, "value"=>4}, {"orderdate"=>2020-11-23 22:56:53 UTC, "value"=>187}], "customer_id"=>"[email protected]"}

結果ドキュメントには、特定のカスタマーからのすべての注文の詳細が、カスタマーのメールアドレス別にグループ化されて含まれます。

1

まず、$match の注文に一致する2020 ステージを追加します。

pipeline.push(doc! {
"$match": {
"orderdate": {
"$gte": DateTime::builder().year(2020).month(1).day(1).build().unwrap(),
"$lt": DateTime::builder().year(2021).month(1).day(1).build().unwrap(),
}
}
});
2

次に、$sort ステージを追加して、orderdate 2020フィールドに昇順の並べ替えを設定し、次のステージで各カスタマー向けの最も近い の購入を取得します。

pipeline.push(doc! {
"$sort": {
"orderdate": 1
}
});
3

$groupフィールドの値で注文ドキュメントを収集するために、customer_id ステージを追加します。このステージでは、結果ドキュメントに次のフィールドを作成する集計操作を追加します。

  • first_purchase_date: カスタマーの最初の購入日

  • total_value: すべてのカスタマーの売上合計値

  • total_orders: カスタマーの購入合計数

  • orders: 各購入の日付と金額を含む、すべてのカスタマーの購入のリスト

pipeline.push(doc! {
"$group": {
"_id": "$customer_id",
"first_purchase_date": { "$first": "$orderdate" },
"total_value": { "$sum": "$value" },
"total_orders": { "$sum": 1 },
"orders": {
"$push": {
"orderdate": "$orderdate",
"value": "$value"
}
}
}
});
4

次に、別の$sort ステージを追加して、first_purchase_date フィールドで昇順の並べ替えを設定します。

pipeline.push(doc! {
"$sort": {
"first_purchase_date": 1
}
});
5

$setステージを追加して、 ステージ中に設定されたcustomer_id フィールドの値から フィールドを再作成します。_id$group

pipeline.push(doc! {
"$set": {
"customer_id": "$_id"
}
});
6

最後に、$unset ステージを追加します。$unset ステージでは、結果ドキュメントから フィールドが削除されます。_id

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

次のコードをアプリケーションの末尾に追加して、 ordersコレクションで集計を実行します。

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

最後に、shell で次のコマンドを実行してアプリケーションを起動します。

cargo run
8

この集計により、2020 年からのカスタマーの注文に関する次の概要が返されます。

Document({"first_purchase_date": DateTime(2020-01-01 8:25:37.0 +00:00:00), "total_value": Int32(63), "total_orders": Int32(1),
"orders": Array([Document({"orderdate": DateTime(2020-01-01 8:25:37.0 +00:00:00), "value": Int32(63)})]), "customer_id": String("[email protected]")})
Document({"first_purchase_date": DateTime(2020-01-13 9:32:07.0 +00:00:00), "total_value": Int32(436), "total_orders": Int32(4),
"orders": Array([Document({"orderdate": DateTime(2020-01-13 9:32:07.0 +00:00:00), "value": Int32(99)}), Document({"orderdate":
DateTime(2020-05-30 8:35:53.0 +00:00:00), "value": Int32(231)}), Document({"orderdate": DateTime(2020-10-03 13:49:44.0 +00:00:00),
"value": Int32(102)}), Document({"orderdate": DateTime(2020-12-26 8:55:46.0 +00:00:00), "value": Int32(4)})]), "customer_id": String("[email protected]")})
Document({"first_purchase_date": DateTime(2020-08-18 23:04:48.0 +00:00:00), "total_value": Int32(191), "total_orders": Int32(2),
"orders": Array([Document({"orderdate": DateTime(2020-08-18 23:04:48.0 +00:00:00), "value": Int32(4)}), Document({"orderdate":
DateTime(2020-11-23 22:56:53.0 +00:00:00), "value": Int32(187)})]), "customer_id": String("[email protected]")})

結果ドキュメントには、特定のカスタマーからのすべての注文の詳細が、カスタマーのメールアドレス別にグループ化されて含まれます。

1

まず、$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"))
)),
2

次に、$sort ステージを追加して、orderdate 2020フィールドに昇順の並べ替えを設定し、次のステージで各カスタマー向けの最も近い の購入を取得します。

Aggregates.sort(Sorts.ascending("orderdate")),
3

$groupフィールドの値で注文ドキュメントを収集するために、customer_id ステージを追加します。このステージでは、結果ドキュメントに次のフィールドを作成する集計操作を追加します。

  • first_purchase_date: カスタマーの最初の購入日

  • total_value: すべてのカスタマーの売上合計値

  • total_orders: カスタマーの購入合計数

  • orders: 各購入の日付と金額を含む、すべてのカスタマーの購入のリスト

Aggregates.group(
"$customer_id",
Accumulators.first("first_purchase_date", "$orderdate"),
Accumulators.sum("total_value", "$value"),
Accumulators.sum("total_orders", 1),
Accumulators.push("orders", Document("orderdate" -> "$orderdate", "value" -> "$value"))
),
4

次に、別の$sort ステージを追加して、first_purchase_date フィールドで昇順の並べ替えを設定します。

Aggregates.sort(Sorts.ascending("first_purchase_date")),
5

$setステージを追加して、 ステージ中に設定されたcustomer_id フィールドの値から フィールドを再作成します。_id$group

Aggregates.set(Field("customer_id", "$_id")),
6

最後に、$unset ステージを追加します。$unset ステージでは、結果ドキュメントから フィールドが削除されます。_id

Aggregates.unset("_id")
7

次のコードをアプリケーションの末尾に追加して、 ordersコレクションで集計を実行します。

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

最後に、アプリケーションを IDE で実行します。

8

この集計により、2020 年からのカスタマーの注文に関する次の概要が返されます。

{"first_purchase_date": {"$date": "2020-01-01T13:25:37Z"}, "total_value": 63, "total_orders": 1, "orders": [{"orderdate": {"$date": "2020-01-01T13:25:37Z"}, "value": 63}], "customer_id": "[email protected]"}
{"first_purchase_date": {"$date": "2020-01-13T14:32:07Z"}, "total_value": 436, "total_orders": 4, "orders": [{"orderdate": {"$date": "2020-01-13T14:32:07Z"}, "value": 99}, {"orderdate": {"$date": "2020-05-30T12:35:52Z"}, "value": 231}, {"orderdate": {"$date": "2020-10-03T17:49:44Z"}, "value": 102}, {"orderdate": {"$date": "2020-12-26T13:55:46Z"}, "value": 4}], "customer_id": "[email protected]"}
{"first_purchase_date": {"$date": "2020-08-19T03:04:48Z"}, "total_value": 191, "total_orders": 2, "orders": [{"orderdate": {"$date": "2020-08-19T03:04:48Z"}, "value": 4}, {"orderdate": {"$date": "2020-11-24T03:56:53Z"}, "value": 187}], "customer_id": "[email protected]"}

結果ドキュメントには、特定のカスタマーからのすべての注文の詳細が、カスタマーのメールアドレス別にグループ化されて含まれます。

戻る

フィルターとサブセット

項目一覧