MongoDB
 Computer >> コンピューター >  >> プログラミング >> MongoDB

MongoDBのaggregate()でドキュメント内の重複値の出現回数を取得する方法

MongoDBで重複値の出現回数を集計する方法

複数のドキュメントにまたがって繰り返し出現する値の件数を取得したい場合は、aggregate()メソッドを使用します。この記事では、実際にコレクションを作成しながら、重複値のカウント方法を段階的に解説します。

1. サンプルコレクションの作成

まず、insertOne()メソッドを使ってドキュメントを挿入し、テスト用のコレクション「demo452」を作成しましょう。

> db.demo452.insertOne({"StudentName":"John","StudentAge":21});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7b7e3371f552a0ebb0a6f3")
}
> db.demo452.insertOne({"StudentName":"John","StudentAge":22});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7b7e3671f552a0ebb0a6f4")
}
> db.demo452.insertOne({"StudentName":"John","StudentAge":23});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7b7e3971f552a0ebb0a6f5")
}
> db.demo452.insertOne({"StudentName":"David","StudentAge":24});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7b7e4371f552a0ebb0a6f6")
}
> db.demo452.insertOne({"StudentName":"David","StudentAge":25});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7b7e4571f552a0ebb0a6f7")
}

2. 登録したドキュメントの確認

find()メソッドを使うと、コレクション内のすべてのドキュメントを表示できます。

> db.demo452.find();

上記のコマンドを実行すると、次のような結果が出力されます。

{ "_id" : ObjectId("5e7b7e3371f552a0ebb0a6f3"), "StudentName" : "John", "StudentAge" : 21 }
{ "_id" : ObjectId("5e7b7e3671f552a0ebb0a6f4"), "StudentName" : "John", "StudentAge" : 22 }
{ "_id" : ObjectId("5e7b7e3971f552a0ebb0a6f5"), "StudentName" : "John", "StudentAge" : 23 }
{ "_id" : ObjectId("5e7b7e4371f552a0ebb0a6f6"), "StudentName" : "David", "StudentAge" : 24}
{ "_id" : ObjectId("5e7b7e4571f552a0ebb0a6f7"), "StudentName" : "David", "StudentAge" : 25}

この時点で、「John」というStudentNameを持つドキュメントが3件、「David」という名前を持つドキュメントが2件登録されていることが確認できます。

3. aggregate()による重複値のカウント

以下は、異なるMongoDBドキュメント間で繰り返される値の数を集計するためのクエリです。$groupステージでStudentNameごとにドキュメントをグループ化し、$sum演算子で各グループの件数をカウントしています。さらに$sortで降順に並べ替え、$projectや$unwindを組み合わせて見やすい形式に整形しています。

> db.demo452.aggregate([
...    {$group: {_id:"$StudentName", count:{$sum:1}}},
...    {$sort: {count:-1}},
...
...    {$group: {_id:1, StudentName:{$push:{StudentName:"$_id", count:"$count"}}}},
...    {$project: {
...       first : {$arrayElemAt: ["$StudentName", 0]},
...       second: {$arrayElemAt: ["$StudentName", 1]},
...       others: {$slice:["$StudentName", 2, {$size: "$StudentName"}]}
...    }
... },
...
... {$project: {
...    status: [
...       "$first",
...       "$second",
...       {
...          StudentName: "New Student Name",
...          count: {$sum: "$others.count"}
...       }
...    ]
... }
... },
...
... {$unwind: "$status"},
... {$project: { _id:0, StudentName: "$status.StudentName", count: "$status.count" }}
... ])

4. 実行結果

上記のパイプラインを実行すると、次のような出力が得られます。

{ "StudentName" : "John", "count" : 3 }
{ "StudentName" : "David", "count" : 2 }
{ "StudentName" : "New Student Name", "count" : 0 }

このように、aggregate()パイプラインを活用することで、ドキュメント内の重複値を効率的に集計できます。特に$group$sumの組み合わせは、データ分析やレポート作成の際に非常に役立つ基本的なテクニックです。ぜひ実際のプロジェクトでも活用してみてください。

  1. 複数のMySQLクエリを1つにまとめて、異なる列ごとの特定値の出現回数を取得する方法

    MySQLでは、SUM()関数と条件式を組み合わせることで、複数のクエリを1つのクエリに統合し、異なる列に含まれる特定の値の出現回数を一度に取得できます。この記事では、具体的な手順をサンプルコード付きで解説します。 テーブルの作成 まず、サンプル用のテーブルを作成します。 mysql> create table DemoTable760 (     ClientId int,     ClientId2 int ); Query OK, 0 rows affected (0.79 sec) レコードの挿入

  2. MySQLで複数の行をカウントし、結果を異なる列(1行)に表示する方法

    はじめにMySQLでは、条件付きのSUM関数を活用することで、複数の行をそれぞれカウントし、その結果を異なる列に横並び(1行)で表示できます。この記事では、色ごとのデータ件数を集計する例をもとに、具体的な手順をわかりやすく解説します。サンプルテーブルを作成するまず、以下のコマンドでテーブルを作成します。ここでは、お気に入りの色を格納する「FavouriteColor」列を持つテーブルを用意しました。mysql> create table DemoTable1452-> (-> FavouriteColor varchar(50)-> );Query OK, 0 rows