在包含多个文档的 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" } ] } ] }
广告