Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
MongoDB Aggregation $first Operator
Next article icon

MongoDB Aggregation $first Operator

Last Updated : 13 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

MongoDB's aggregation framework offers a rich set of operators for data manipulation and analysis. One such operator is $first, which retrieves the first document from a group of documents.

In this article, we will learn about the $first operator in MongoDB aggregation by covering its concepts and usage with beginner-friendly examples.

MongoDB Aggregation $first

MongoDB Aggregation $first operator retrieves the first document from a group of documents based on a specified sorting order. This allows us to extract specific data points or summaries from grouped data sets.

It is commonly used in conjunction with the $group stage to group documents by a specific field or expression and then extract the first document from each group. This is useful for creating summaries or extracting key information from grouped data.

The MongoDB Aggregation $first operator is used within the $group stage of an aggregation pipeline. It takes the form { $first: "$fieldName" } where "fieldName" is the name of the field whose value we want to extract from the first document in each group.

Syntax:

{
$group: {
_id: <expression>,
firstField: { $first: "$fieldName" }
}
}

Explanation:

  • _id: The field or expression used to group documents.
  • firstField: The output field that will contain the first document from each group.
  • $first: "$fieldName": The $first operator indicates that the value of the specified field (fieldName) from the first document in each group should be returned.

Let's set up an Environment:

To understand MongoDB Aggregation $first Operator we need a collection and some documents on which we will perform various operations and queries. Here we will consider a collection called students which contains information in various documents are shown below.

([
... { "name": "Alice", "age": 18, "grade": 10 },
... { "name": "Bob", "age": 17, "grade": 10 },
... { "name": "Charlie", "age": 16, "grade": 11 },
... { "name": "David", "age": 18, "grade": 11 },
... { "name": "Eva", "age": 17, "grade": 12 },
... { "name": "Frank", "age": 16, "grade": 12 }
... ])

Example of MongoDB Aggregation $first Operator

Suppose we We want to find the oldest student in each grade. Here's how we can use the $first operator to achieve this:

db.students.aggregate([
{
$group: {
_id: "$grade",
oldestStudent: { $first: "$name" }
}
}
])

Output:

[
{ "_id": 10, "oldestStudent": "Alice" },
{ "_id": 11, "oldestStudent": "Charlie" },
{ "_id": 12, "oldestStudent": "Eva" }
]

Explanation:

  • $group groups documents by the grade field.
  • $first: "$name" retrieves the value of the name field from the first document in each group, which corresponds to the oldest student in that grade.
  • This output shows the oldest student in each grade based on the first document encountered during grouping.

Handling Multiple Fields

The $first operator can be used with multiple fields to retrieve the first document containing specific values.

Example:

Suppose we want to find the first and last names of the oldest student in each grade. We can use the $first operator multiple times within the $group stage.

db.students.aggregate([
{
$group: {
_id: "$grade",
oldestStudentFirst: { $first: "$name" },
oldestStudentLast: { $last: "$name" }
}
}
])

Output:

[
{ "_id": 10, "oldestStudentFirst": "Alice", "oldestStudentLast": "Bob" },
{ "_id": 11, "oldestStudentFirst": "Charlie", "oldestStudentLast": "David" },
{ "_id": 12, "oldestStudentFirst": "Eva", "oldestStudentLast": "Frank" }
]

Explanation: In this example, we use $first to retrieve the first name and $last to retrieve the last name of the oldest student in each grade.

Conclusion

Overall, understanding the MongoDB Aggregation $first operator allows for efficient data extraction and summarization within MongoDB's aggregation framework. By using this operator developers can quickly derive insights such as identifying the first occurrence of specific data points within grouped data sets. Understanding its syntax and usage scenarios enhances the ability to perform complex data aggregations and analyses in MongoDB.


Next Article
MongoDB Aggregation $first Operator

K

kumarsar29u2
Improve
Article Tags :
  • MongoDB
  • Databases

Similar Reads

    MongoDB Aggregation $out
    MongoDB's aggregation framework offers powerful tools for data analysis and the $out stage for data processing and analysis, with the $out stage playing a crucial role in persistently storing the results of an aggregation pipeline. This feature is highly beneficial for efficient data analysis, repor
    5 min read
    Python MongoDB - $group (aggregation)
    MongoDB is an open-source document-oriented database. MongoDB stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. In this article, we will see the use of $group in MongoDB using Python. $group operation In PyMongo, the Aggregate Method is
    3 min read
    Aggregation in MongoDB
    Aggregation in MongoDB is a powerful framework that allows developers to perform complex data transformations, computations and analysis on collections of documents. By utilizing the aggregation pipeline, users can efficiently group, filter, sort, reshape, and perform calculations on data to generat
    7 min read
    MongoDB $addToSet Operator
    The $addToSet operator in MongoDB allows us to add elements to an array field if they are not already present and ensure that the array contains unique values.In this article, We will learn about the MongoDB $addToSet Operator by understanding various examples in detail.$addToSet Operator in MongoDB
    3 min read
    MongoDB Aggregation Pipeline $limit
    The MongoDB aggregation pipeline is a powerful tool for data processing and transformation, allowing users to perform efficient filtering, sorting, grouping, and reshaping of documents. Among its various stages, the $limit stage is essential for restricting the number of documents that flow through
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences