あいつの日誌β

あいつの日誌です。

mongodb の aggregate

grouping したときのメモ

% mongo --version
MongoDB shell version: 2.6.1
% mongod --version
db version v2.6.1
2014-05-13T08:53:12.464+0900 git version: nogitversion
use test_db
db.dropDatabase();
db.testaggregate.insert(
{
    'a': 1,
});
db.testaggregate.insert(
{
    'a': 2,
});
db.testaggregate.insert(
{
    'a': 2,
});
db.testaggregate.insert(
{
    'a': 3,
}
);
db.testaggregate.insert(
{
    'a': 3,
}
);
db.testaggregate.insert(
{
    'a': 3,
}
);

grouping

db.testaggregate.aggregate({ 
    $group : {
        _id : "$a",
        count: {$sum: 1}
    }
});

{ "_id" : 3, "count" : 3 }
{ "_id" : 2, "count" : 2 }
{ "_id" : 1, "count" : 1 }

_id を保持したい場合は以下のようにするそうな

db.testaggregate.aggregate(
    {
        $group : {
            _id : "$a",
            count: {$sum: 1},
            originalIds: { $push: "$_id" }
        }
    }
);
{ "_id" : 3, "count" : 3, "originalIds" : [ ObjectId("5371651bedeb7279703bc565"), ObjectId("5371651bedeb7279703bc566"), ObjectId("5371651bedeb7279703bc567") ] }
{ "_id" : 2, "count" : 2, "originalIds" : [ ObjectId("5371651bedeb7279703bc563"), ObjectId("5371651bedeb7279703bc564") ] }
{ "_id" : 1, "count" : 1, "originalIds" : [ ObjectId("5371651aedeb7279703bc562") ] }

SEE ALSO

http://docs.mongodb.org/manual/reference/operator/aggregation/push/