Return whole document from aggregation

aggregation-framework, mongodb

Solution

Currently you cannot get the whole `comment` document via single `$first` operator. But you can include other necessary fields (similar to `_id` field) during `$group` step:

{
    "$group": {
        _id: "$post_id",
        lastComment: { "$first": "$_id" },
        field_1: { "$first": "$field_1" },
        field_2: { "$first": "$field_2" },
        // ...
        field_N: { "$first": "$field_N" }
    }
}

According to this JIRA ticket: https://jira.mongodb.org/browse/SERVER-5916, the whole document will be available to return from aggregation operations from 2.5.3 version. It will be possible using new variables: `$$ROOT` or `$$CURRENT`:

{
    "$group": {
        _id: "$post_id",
        lastComment: { "$first": "$$CURRENT" }
    }
}

Problem

I'm using the following query to fetch one most recent comment for every post in database: ``` db.comments.aggregate([ { "$match": { "post_id": { "$in": [ObjectId("52c5ce24dca32d32740c1435"), ObjectId("52c5ce24dca32d32740c15ad")] } } }, { "$sort": {"_id": -1} }, { "$group": { "_id": "$post_id", "lastComment": { "$first": "$_id" } } } ]) ``` I expect it to return the whole comment's document but it only returns the `_id` field of each document. So what would be the proper way to get all most recent comments as a whole document (or at least include some other fields)?

Original source