(MongoDB) MongoDB의 $group 사용법

$group 에서 _Id 필드는 유니크 키로 사용되며 distinct값으로 사용된다.


_Id 필드는 의무적이다.


* $push 는 각 표현의 값을 배열형식으로 집어넣는다.(각각의 키에 해당하는 document에 따라)


예제)

sales라는 collection이 주어졌을 때,


{ "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-03-01T08:00:00Z") }
{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-03-01T09:00:00Z") }
{ "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-03-15T09:00:00Z") }
{ "_id" : 4, "item" : "xyz", "price" : 5, "quantity" : 20, "date" : ISODate("2014-04-04T11:21:39.736Z") }
{ "_id" : 5, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-04-04T21:23:13.331Z") }


Q) 년, 월, 일 을 Group Key로 하고, 총가격, 평균 가격을 나타내는 값을 리턴하라.

db.sales.aggregate({
{"$group" : {
_id : {month : {$month:"$date"}, day : {$dayOfMonth: "$date"}, year : {$year: "$date"}},
totalPrices : {$sum : {$multiply : ["$price", "$quantity"]}},
averageQuantity : {$avg : "$quantity"},
count : {$sum : 1}
}}
})




<Groupy by null>

_id를 null 로 하게 되면 모든 도큐멘트에 대해 해당 계산을 진행하게 된다.


db.sales.aggregate({
{"$group" : {
_id : null,
totalPrices : {$sum : {$multiply : ["$price", "$quantity"]}},
averageQuantity : {$avg : "$quantity"},
count : {$sum : 1}
}}
})


결과 : { "_id" : null, "totalPrice" : 290, "averageQuantity" : 8.6, "count" : 5 }



<Retrieve Distinct Values>


db.sales.aggregate([
{$group : {_id : "$item"}}

])


다음과 같은 결과를 얻는다.


{ "_id" : "xyz" }
{ "_id" : "jkl" }

{ "_id" : "abc" }


<Pivot Data>

collection이 book 인 다음과 같은 입력값들이 있다.


{ "_id" : 8751, "title" : "The Banquet", "author" : "Dante", "copies" : 2 }
{ "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 }
{ "_id" : 8645, "title" : "Eclogues", "author" : "Dante", "copies" : 2 }
{ "_id" : 7000, "title" : "The Odyssey", "author" : "Homer", "copies" : 10 }

{ "_id" : 7020, "title" : "Iliad", "author" : "Homer", "copies" : 10 }

author별 title로 분류 하자.


db.book.aggregate([
{"$group" : {
_id:"$author"
books : {$push : "$title"}
}}
])


결과 : 
{ "_id" : "Homer", "books" : [ "The Odyssey", "Iliad" ] }
{ "_id" : "Dante", "books" : [ "The Banquet", "Divine Comedy", "Eclogues" ] }



<Group Documents by author>

db.books.aggregate(
   [
     { $group : { _id : "$author", books: { $push: "$$ROOT" } } }
   ]
)




결과는 다음과 같다.


{
  "_id" : "Homer",
  "books" :
     [
       { "_id" : 7000, "title" : "The Odyssey", "author" : "Homer", "copies" : 10 },
       { "_id" : 7020, "title" : "Iliad", "author" : "Homer", "copies" : 10 }
     ]
}

{
  "_id" : "Dante",
  "books" :
     [
       { "_id" : 8751, "title" : "The Banquet", "author" : "Dante", "copies" : 2 },
       { "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 },
       { "_id" : 8645, "title" : "Eclogues", "author" : "Dante", "copies" : 2 }
     ]
}









댓글

이 블로그의 인기 게시물

(네트워크)폴링방식 vs 롱 폴링방식

(ElasticSearch) 결과에서 순서 정렬

(18장) WebSocekt과 STOMP를 사용하여 메시징하기