集計結果を取得し、さまざまなMongoDBドキュメントで繰り返される値の数を見つけます
さまざまなドキュメントで繰り返される値の数を取得するには、aggregate()を使用します。ドキュメントを使用してコレクションを作成しましょう-
> 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")
} 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} 以下は、さまざまなMongoDBドキュメントで繰り返される値の数を見つけるためのクエリです-
> 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" }}
... ]) これにより、次の出力が生成されます-
{ "StudentName" : "John", "count" : 3 }
{ "StudentName" : "David", "count" : 2 }
{ "StudentName" : "New Student Name", "count" : 0 } -
クエリを単一のMySQLクエリにマージして、さまざまな列のさまざまな値の数を取得するにはどうすればよいですか?
まずテーブルを作成しましょう- mysql> create table DemoTable760 ( ClientId int, ClientId2 int ); Query OK, 0 rows affected (0.79 sec) 挿入コマンド-を使用して、テーブルにいくつかのレコードを挿入します mysql> insert into DemoTable760 values(100,200); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTab
-
MySQLを使用して、複数の行をカウントし、結果を異なる列(および単一の行)に表示します
まずテーブルを作成しましょう- mysql> create table DemoTable1452 -> ( -> FavouriteColor varchar(50) -> ); Query OK, 0 rows affected (2.42 sec) 挿入コマンド-を使用して、テーブルにいくつかのレコードを挿入します mysql> insert into DemoTable1452 values('Red'); Query OK, 1 row affected (0