MongoDB集計で複数のフィールドでカウント
複数のフィールドでカウントするには、MongoDBで$facetを使用します。 $ facetは、同じ入力ドキュメントのセットの単一ステージ内で複数の集約パイプラインを処理します。ドキュメントを使用してコレクションを作成しましょう-
> db.demo721.insertOne(
... {
...
... "details1": {
... "id":101
...
... },
... "details2": {
... "id":101
... },
... "details3": {
... "id":101
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5eaaebdd43417811278f5887")
}
>
>
> db.demo721.insertOne(
... {
...
... "details1": {
... "id":101
...
... },
... "details2": {
... "id":102
... },
... "details3": {
... "id":102
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5eaaebe943417811278f5888")
} find()メソッドを使用してコレクションからすべてのドキュメントを表示する-
> db.demo721.find();
これにより、次の出力が生成されます-
{ "_id" : ObjectId("5eaaebdd43417811278f5887"), "details1" : { "id" : 101 }, "details2" : { "id" : 101 }, "details3" : { "id" : 101 } }
{ "_id" : ObjectId("5eaaebe943417811278f5888"), "details1" : { "id" : 101 }, "details2" : { "id" : 102 }, "details3" : { "id" : 102 } } 以下は、複数のフィールドでカウントするクエリです-
> db.demo721.aggregate([
... {$facet:{
... ids:[
... {$group:{ _id:null,
... d3:{$addToSet: "$details3.id"},
... d2:{$addToSet:"$details2.id"},
... d1:{$addToSet:"$details1.id"}}},
... {$project:{ _id:0,
... listofall:{$setUnion:["$d1","$d2","$d3"]}}}],
... d:[{$project:{ _id:0,
... a1:"$details1.id",
... a2:"$details2.id",
... a3:"$details3.id"}}]}},
... {$unwind:"$d"},
... {$unwind:"$ids"},
... {$unwind:"$ids.listofall"},
... {$group:{ _id:"$ids.listofall",
... details1id:{$sum:{$cond:[{$eq:["$d.a1","$ids.listofall"]},1,0]}},
... details2id:{$sum:{$cond:[{$eq:["$d.a2","$ids.listofall"]},1,0]}},
... details3id:{$sum:{$cond:[{$eq:["$d.a3","$ids.listofall"]},1,0]}}}}]) これにより、次の出力が生成されます-
{ "_id" : 102, "details1id" : 0, "details2id" : 1, "details3id" : 1 }
{ "_id" : 101, "details1id" : 2, "details2id" : 1, "details3id" : 1 } -
フィールドを結合またはマージしてからカウントするMongoDB集約?
フィールドを結合またはマージしてからカウントを実行するには、$groupを$sumおよび$sortとともに使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo647.insertOne({"Subject":"MySQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5e9c86316c954c74be91e6ee") } > db.dem
-
複数の列を持つMySQLの複数のCOUNT?
集計関数SUM()をIF()と一緒に使用できます。まずテーブルを作成しましょう- mysql> create table DemoTable ( FirstName varchar(100), LastName varchar(100) ); Query OK, 0 rows affected (2.80 sec) 挿入コマンド-を使用して、テーブルにいくつかのレコードを挿入します mysql> insert into DemoTable values('Adam','Smith'); Query