How to returns first sorted group document

Hi,
I have the following pipeline as in the example at: https://docs.mongodb.com/manual/reference/operator/aggregation/first/

db.sales.aggregate(
   [
     { $sort: { item: 1, date: 1 } },
     {
       $group:
         {
           _id: "$item",
           firstSalesDate: { $first: "$date" }
         }
     }
   ]
)

But now, I want to return for each “item” the whole document that associates with the group results

Thanks,
Itzhak

Hello @Itzhak_Kagan Welcome back,

You can get a document using $$ROOT,

{
    $group: {
        _id: "$item",
        firstItem: { $first: "$$ROOT" }
    }
}

For array of documents using $push and $$ROOT,

{
    $group: {
        _id: "$item",
        allItems: { $push: "$$ROOT" }
    }
}

For more information you can checkout $gruop docs

Thanks @Vishal Turi
It was a very fast and helpful reply.
You have a great knowledge.

Thanks a lot,
Itzhak

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.