如何在 MongoDB 中汇总集合并按字段计数进行分组?
在 MongoDB aggregate() 中,使用 $group 和聚合集合。我们用文档创建一个集合:
> db.demo616.insertOne({"details":{"Name":"Chris","Age":21}}); { "acknowledged" : true, "insertedId" : ObjectId("5e99bfac65492f6c60d00283") } > db.demo616.insertOne({"details":{"Name":"Chris","Age":22}}); { "acknowledged" : true, "insertedId" : ObjectId("5e99bfb065492f6c60d00284") } > db.demo616.insertOne({"details":{"Name":"Bob","Age":23}}); { "acknowledged" : true, "insertedId" : ObjectId("5e99bfb865492f6c60d00285") } > db.demo616.insertOne({"details":{"Name":"Sam","Age":21}}); { "acknowledged" : true, "insertedId" : ObjectId("5e99bfbd65492f6c60d00286") } > db.demo616.insertOne({"details":{"Name":"Chris","Age":24}}); { "acknowledged" : true, "insertedId" : ObjectId("5e99bfc165492f6c60d00287") }
使用 find() 方法显示集合中的所有文档:
> db.demo616.find();
这将生成以下输出:
{ "_id" : ObjectId("5e99bfac65492f6c60d00283"), "details" : { "Name" : "Chris", "Age" : 21 } } { "_id" : ObjectId("5e99bfb065492f6c60d00284"), "details" : { "Name" : "Chris", "Age" : 22 } } { "_id" : ObjectId("5e99bfb865492f6c60d00285"), "details" : { "Name" : "Bob", "Age" : 23 } } { "_id" : ObjectId("5e99bfbd65492f6c60d00286"), "details" : { "Name" : "Sam", "Age" : 21 } } { "_id" : ObjectId("5e99bfc165492f6c60d00287"), "details" : { "Name" : "Chris", "Age" : 24 } }
以下是根据字段计数聚合集合并分组的查询:
> db.demo616.aggregate( ... [ ... { ... $group:{_id:"$details.Name",Total:{$sum:1}}} ... ] ... );
这将生成以下输出:
{ "_id" : "Sam", "Total" : 1 } { "_id" : "Bob", "Total" : 1 } { "_id" : "Chris", "Total" : 3 }
广告