MongoDB聚合来组合或合并字段,然后进行计数?
为了合并或合并字段然后执行计数,使用 $group 以及 $sum 和 $sort。让我们用文档创建一个集合 -
> db.demo647.insertOne({"Subject":"MySQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5e9c86316c954c74be91e6ee") } > db.demo647.insertOne({"Subject":"MongoDB"}); { "acknowledged" : true, "insertedId" : ObjectId("5e9c86356c954c74be91e6ef") } > db.demo647.insertOne({"Subject":"MySQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5e9c86376c954c74be91e6f0") } > db.demo647.insertOne({"Subject":"SQL Server"}); { "acknowledged" : true, "insertedId" : ObjectId("5e9c86406c954c74be91e6f1") } > db.demo647.insertOne({"Subject":"MongoDB"}); { "acknowledged" : true, "insertedId" : ObjectId("5e9c86436c954c74be91e6f2") } > db.demo647.insertOne({"Subject":"PL/SQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5e9c864b6c954c74be91e6f3") } > db.demo647.insertOne({"Subject":"MongoDB"}); { "acknowledged" : true, "insertedId" : ObjectId("5e9c86c16c954c74be91e6f4") }
使用 find() 方法从集合中显示所有文档 -
> db.demo647.find();
这将生成以下输出 -
{ "_id" : ObjectId("5e9c86316c954c74be91e6ee"), "Subject" : "MySQL" } { "_id" : ObjectId("5e9c86356c954c74be91e6ef"), "Subject" : "MongoDB" } { "_id" : ObjectId("5e9c86376c954c74be91e6f0"), "Subject" : "MySQL" } { "_id" : ObjectId("5e9c86406c954c74be91e6f1"), "Subject" : "SQL Server" } { "_id" : ObjectId("5e9c86436c954c74be91e6f2"), "Subject" : "MongoDB" } { "_id" : ObjectId("5e9c864b6c954c74be91e6f3"), "Subject" : "PL/SQL" } { "_id" : ObjectId("5e9c86c16c954c74be91e6f4"), "Subject" : "MongoDB" }
以下是合并或合并字段然后计数的查询 -
> db.demo647.aggregate([ { "$group": { "_id": "$Subject", "COUNT": { "$sum": 1 } } }, { "$sort": { "COUNT": -1 } }, { "$limit": 2 } ] );
这将生成以下输出 -
{ "_id" : "MongoDB", "COUNT" : 3 } { "_id" : "MySQL", "COUNT" : 2 }
广告