Q:

native reverse links in mongodb

For example I created post with two comments:
db.posts.save(id: 'xxx');
db.comments.save(id:'c1', post: 'xxx', text: 'first comment');
db.comments.save(id:'c2', post: 'xxx', text: 'second comment');

I want to get data about comments in posts.find(): 
[{id: 'xxx', commentsCount: 2}]

or better:
[{id: 'xxx', comments:['c1', 'c2']}]

I want to do it with native mongodb methods (without manual updating of collection 'posts'). Read about DbRefs and MapReduce, but didnt understand how to solve my task. 

A:

When you want to retrieve documents in a transformed manner, you are looking for the aggregation framework.
First you use the $match operator to narrow the aggregation down to the relevant documents. In this case you want to create one document based on many, so you need the $group operator.
This would give you a document with an array for a specific post:
db.comments.aggregate([
    { $match: {
            post:'xxx'
        }
    },
    { $group: {
            id: "$post",
            comments: { $push: "$text" }
        }
    },
]);

This would give you a document with a count:
db.comments.aggregate([
    { $match: {
            post:'xxx'
        }
    },
    { $group: {
            id: "$post",
            commentsCount: { $sum: 1 }
        }
    },
]);

