Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Get the first element in an array and return using MongoDB Aggregate?
To get the first element from an array using MongoDB aggregation, use the $arrayElemAt operator or combine $unwind with $first. The $arrayElemAt method is simpler and more efficient for this task.
Syntax
db.collection.aggregate([
{
$project: {
"fieldName": { $arrayElemAt: ["$arrayField", 0] }
}
}
]);
Sample Data
db.getFirstElementInArrayDemo.insertMany([
{
"StudentName": "John",
"StudentSubject": ["MongoDB", "Python", "MySQL"]
},
{
"StudentName": "Chris",
"StudentSubject": ["Java", "C"]
},
{
"StudentName": "Robert",
"StudentSubject": ["C++", "Ruby"]
}
]);
Method 1: Using $arrayElemAt (Recommended)
Get the first element from each array using $arrayElemAt with index 0 ?
db.getFirstElementInArrayDemo.aggregate([
{
$project: {
"_id": 0,
"StudentName": 1,
"FirstSubject": { $arrayElemAt: ["$StudentSubject", 0] }
}
}
]);
{ "StudentName": "John", "FirstSubject": "MongoDB" }
{ "StudentName": "Chris", "FirstSubject": "Java" }
{ "StudentName": "Robert", "FirstSubject": "C++" }
Method 2: Using $unwind and $first
Alternative approach using $unwind to deconstruct arrays, then $first to get the first element ?
db.getFirstElementInArrayDemo.aggregate([
{ $unwind: "$StudentSubject" },
{
$group: {
"_id": "$_id",
"StudentName": { $first: "$StudentName" },
"FirstElement": { $first: "$StudentSubject" }
}
},
{ $project: { "_id": 0, "StudentName": 1, "FirstElement": 1 } }
]);
{ "StudentName": "John", "FirstElement": "MongoDB" }
{ "StudentName": "Chris", "FirstElement": "Java" }
{ "StudentName": "Robert", "FirstElement": "C++" }
Alternative: Using $slice in find()
For simple queries without aggregation, use $slice to limit array elements ?
db.getFirstElementInArrayDemo.find(
{},
{ "StudentSubject": { $slice: 1 } }
);
{ "_id": ObjectId("..."), "StudentName": "John", "StudentSubject": ["MongoDB"] }
{ "_id": ObjectId("..."), "StudentName": "Chris", "StudentSubject": ["Java"] }
{ "_id": ObjectId("..."), "StudentName": "Robert", "StudentSubject": ["C++"] }
Key Points
-
$arrayElemAtis the most efficient method for accessing array elements by index. -
$unwind+$firstrequires more pipeline stages but offers flexibility for complex operations. -
$sliceinfind()returns the element within an array, not as a single value.
Conclusion
Use $arrayElemAt with index 0 for the simplest and most efficient way to get the first array element. The $unwind approach provides more control when you need additional array processing in your aggregation pipeline.
Advertisements
