집계 작업은 여러 문서의 값을 함께 그룹화하고 그룹화된 데이터에 대해 다양한 작업을 수행하여 단일 결과를 반환할 수 있습니다.
MongoDB에서 집계하려면 집계()를 사용합니다. 문서로 컬렉션을 만들자 −
> 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"
}
]
}
]
}