Articles → MONGODB → $First And $Last Aggregation Operators In Mongodb

$First And $Last Aggregation Operators In Mongodb






Purpose







Example




Picture showing the sample documents in mongodb






db.orders.aggregate([   
    {
        $group: {
            _id: "$customerId",
            firstOrderId: { $first: "$_id" }
        }
    }
])


Picture showing the output of $first aggregation operator in mongodb




db.orders.aggregate([   
    {
        $group: {
            _id: "$customerId",
            firstOrderId: { $last: "$_id" }
        }
    }
])


Picture showing the output of $last aggregation operator in mongodb



Posted By  -  Karan Gupta
 
Posted On  -  Friday, June 7, 2024

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250