在包含多个文档的MongoDB集合中按国家,州和城市进行汇总
聚合操作将来自多个文档的值分组在一起,并且可以对分组的数据执行各种操作以返回单个结果。
要在MongoDB中聚合,请使用aggregate()
。让我们创建一个包含文档的集合-
> db.demo620.insertOne({"Country":"IND","City":"Delhi",state:"Delhi"}); { "acknowledged" : true, "insertedId" : ObjectId("5e9a8de96c954c74be91e6a1") } > db.demo620.insertOne({"Country":"IND","City":"Bangalore",state:"Karnataka"}); { "acknowledged" : true, "insertedId" : ObjectId("5e9a8e336c954c74be91e6a3") } > db.demo620.insertOne({"Country":"IND","City":"Mumbai",state:"Maharashtra"}); { "acknowledged" : true, "insertedId" : ObjectId("5e9a8e636c954c74be91e6a4") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo620.find();
这将产生以下输出-
{ "_id" : ObjectId("5e9a8de96c954c74be91e6a1"), "Country" : "IND", "City" : "Delhi", "state" : "Delhi" } { "_id" : ObjectId("5e9a8e336c954c74be91e6a3"), "Country" : "IND", "City" : "Bangalore", "state" : "Karnataka" } { "_id" : ObjectId("5e9a8e636c954c74be91e6a4"), "Country" : "IND", "City" : "Mumbai", "state" : "Maharashtra" }
以下是按国家,州和城市汇总的查询-
> db.demo620.aggregate([ ... { "$group": { ... "_id": { ... "Country": "$Country", ... "state": "$state" ... }, ... "City": { ... "$addToSet": { ... "City": "$City" ... } ... } ... }}, ... { "$group": { ... "_id": "$_id.Country", ... "states": { ... "$addToSet": { ... "state": "$_id.state", ... "City": "$City" ... } ... } ... }} ... ]).pretty();
这将产生以下输出-
{ "_id" : "IND", "states" : [ { "state" : "Delhi", "City" : [ { "City" : "Delhi" } ] }, { "state" : "Maharashtra", "City" : [ { "City" : "Mumbai" } ] }, { "state" : "Karnataka", "City" : [ { "City" : "Bangalore" } ] } ] }