単一のMongoDBクエリでグループと個別を一緒に実行します
これには、MongoDB$groupを使用するだけです。まず、ドキュメントを使用してコレクションを作成しましょう-
> db.demo16.insertOne({
... "StudentName" : "Chris",
... "StudentSection" : "A",
... "StudentAge" : 23,
... "StudentMarks" : 47
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e13827455d0fc6657d21f07")
}
> db.demo16.insertOne({
... "StudentName" : "Bob",
... "StudentSection" : "B",
... "StudentAge" : 21,
... "StudentMarks" : 85
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e13827555d0fc6657d21f08")
}
> db.demo16.insertOne( {
... "StudentName" : "Carol",
... "StudentSection" : "A",
... "StudentAge" : 26,
... "StudentMarks" : 97
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e13827655d0fc6657d21f09")
} 以下は、find()メソッドを使用してコレクションからすべてのドキュメントを表示するためのクエリです-
> db.demo16.find().pretty();
これにより、次の出力が生成されます-
{
"_id" : ObjectId("5e13827455d0fc6657d21f07"),
"StudentName" : "Chris",
"StudentSection" : "A",
"StudentAge" : 23,
"StudentMarks" : 47
}
{
"_id" : ObjectId("5e13827555d0fc6657d21f08"),
"StudentName" : "Bob",
"StudentSection" : "B",
"StudentAge" : 21,
"StudentMarks" : 85
}
{
"_id" : ObjectId("5e13827655d0fc6657d21f09"),
"StudentName" : "Carol",
"StudentSection" : "A",
"StudentAge" : 26,
"StudentMarks" : 97
} 以下は、グループ操作と個別操作を一緒に実装するためのクエリです-
> db.demo16.aggregate([{
... $group : {
... _id : null,
... StudentName : { $addToSet : "$StudentName" },
... StudentSection : { $addToSet : "$StudentSection" },
... StudentMinimumAge : { $min : "$StudentAge" },
... StudentMaximumAge : { $max : "$StudentAge" },
... StudentMinimumMarks: { $min : "$StudentMarks" },
... StudentMaximumMarks : { $max : "$StudentMarks" }
... }
... }]).pretty(); これにより、次の出力が生成されます-
{
"_id" : null,
"StudentName" : [
"Carol",
"Bob",
"Chris"
],
"StudentSection" : [
"B",
"A"
],
"StudentMinimumAge" : 21,
"StudentMaximumAge" : 26,
"StudentMinimumMarks" : 47,
"StudentMaximumMarks" : 97
} -
MySQL COUNT()とDISTINCTを一緒に使用できますか?
はい、COUNT()とDISTINCTを一緒に使用して、個別の行のみのカウントを表示できます。 構文は次のとおりです- SELECT COUNT(DISTINCT yourColumnName) AS anyVariableName FROM yourTableName; 上記の構文を理解するために、テーブルを作成しましょう。 テーブルを作成するためのクエリは次のとおりです- mysql> create table CountDistinctDemo -> ( -> Id int NOT NULL AUTO_INC
-
Idによって区別されるconcatをグループ化するMySQLクエリ?
まずテーブルを作成しましょう- mysql> create table DemoTable ( Id int, Name varchar(100) ); Query OK, 0 rows affected (0.64 sec) 挿入コマンド-を使用して、テーブルにいくつかのレコードを挿入します mysql> insert into DemoTable values(100,'Chris'); Query OK, 1 row affected (0.44 sec) mysql> insert into Dem