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
How to use $slice operator to get last element of array in MongoDB?
To get the last element of an array in MongoDB, use the $slice operator with -1 in the projection. This returns only the last element of the specified array field.
Syntax
db.collectionName.find(
{},
{ arrayFieldName: { $slice: -1 } }
);
Sample Data
Let us create a collection with sample student documents ?
db.getLastElementOfArrayDemo.insertMany([
{
"StudentName": "James",
"StudentMathScore": [78, 68, 98]
},
{
"StudentName": "Chris",
"StudentMathScore": [88, 56, 34]
},
{
"StudentName": "Larry",
"StudentMathScore": [99]
},
{
"StudentName": "Robert",
"StudentMathScore": [90, 78, 67, 66, 75, 73]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c9d2d71a629b87623db1b2e"),
ObjectId("5c9d2d83a629b87623db1b2f"),
ObjectId("5c9d2d8ea629b87623db1b30"),
ObjectId("5c9d2dada629b87623db1b31")
]
}
View All Documents
db.getLastElementOfArrayDemo.find().pretty();
{
"_id": ObjectId("5c9d2d71a629b87623db1b2e"),
"StudentName": "James",
"StudentMathScore": [78, 68, 98]
}
{
"_id": ObjectId("5c9d2d83a629b87623db1b2f"),
"StudentName": "Chris",
"StudentMathScore": [88, 56, 34]
}
{
"_id": ObjectId("5c9d2d8ea629b87623db1b30"),
"StudentName": "Larry",
"StudentMathScore": [99]
}
{
"_id": ObjectId("5c9d2dada629b87623db1b31"),
"StudentName": "Robert",
"StudentMathScore": [90, 78, 67, 66, 75, 73]
}
Get Last Array Element
Use $slice: -1 to retrieve only the last element from each array ?
db.getLastElementOfArrayDemo.find(
{},
{ StudentMathScore: { $slice: -1 } }
);
{ "_id": ObjectId("5c9d2d71a629b87623db1b2e"), "StudentName": "James", "StudentMathScore": [98] }
{ "_id": ObjectId("5c9d2d83a629b87623db1b2f"), "StudentName": "Chris", "StudentMathScore": [34] }
{ "_id": ObjectId("5c9d2d8ea629b87623db1b30"), "StudentName": "Larry", "StudentMathScore": [99] }
{ "_id": ObjectId("5c9d2dada629b87623db1b31"), "StudentName": "Robert", "StudentMathScore": [73] }
Key Points
-
$slice: -1returns the last element as a single-element array, not a scalar value. - Works with arrays of any size, including single-element arrays.
- Can be combined with query filters to target specific documents.
Conclusion
The $slice operator with -1 efficiently retrieves the last element from array fields. The result is returned as an array containing only the last element, preserving the array structure in the output.
Advertisements
