2013. 1. 4. 11:02

[MongoDB] Aggregation Framework

MongoDB 의 MR(map reduce) 은 serialization/deserialization 으로 인해 그다지 빠르지 않았습니다.

그래서 MongoDB 2.1 부터 성능을 개선한 aggregation framework 가 추가되었습니다.


MongoDB MR (Map Reduce) has performance issue because of serialization and deserialization.

Instead of MR, Aggregation Framework is added to MongoDB 2.1 or newer.


아래의 내용의 출처는 http://docs.mongodb.org/manual/applications/aggregation/ 입니다. 

더 자세한 내용은 위의 링크에서 볼 수 있습니다.


The reference of this post is http://docs.mongodb.org/manual/applications/aggregation/.

You can find the details on the mongodb manual.


MongoDB 의 aggregation framework 를 사용하는 방법은 아래와 같습니다:

Simple example is:


db.articles.aggregate(
    { $project : {

        author : 1,
        tags : 1

    } },
    { $unwind : "$tags" },
    { $group : {
        _id : { tags : "$tags" },
        authors : { $addToSet : "$author" }
    } }
);


위의 예제는 articles collection 에서 author 와 tags 필드를 선택하여 각 tag 별 author 의 집합을 리턴합니다.

This example pivots data to create a set of author names grouped by tags applied to an article.


$unwind 는 배열로 된 필드를 분리하여 하나의 문서를 여러 개의 문서로 만들어 줍니다.

$unwind peels off the element of an array individually, and return a stream of documents.


{"title": "this is my title", "author": "bob", "tags": ["fun", "good"]}


이 문서에 aggregate({ $project : author : 1, tags : 1}}, $unwind : "$tags"}) 를 적용하면 아래와 같은 결과를 얻을 수 있습니다.

Following documents are the result of aggregate({ $project : author : 1, tags : 1}}, $unwind : "$tags"}) with abovementioned document.


{

    "result": [

        {"author": "bob", "tags": "fun"},

        {"author": "bob", "tags": "good"}],

    "ok": 1

}


참고로 spring-data 는 aggregation framework 를 지원하지 않으니 mongodb java driver 를 이용하시길 바랍니다.

참고: http://www.mongodb.org/display/DOCS/Using+The+Aggregation+Framework+with+The+Java+Driver