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
Aggregate a $slice to get an element in exact position from a nested array in MongoDB?
To get an element from an exact position in a nested array using MongoDB's aggregation framework, use the $slice operator within a $project stage to extract specific elements by their index position.
Syntax
db.collection.aggregate([
{
$project: {
"arrayField": { $slice: ["$arrayField", startIndex, numberOfElements] }
}
}
]);
Sample Data
db.exactPositionDemo.insertOne({
"StudentName": "John",
"StudentScores": [78, 98, 56, 45, 89]
});
{
"acknowledged": true,
"insertedId": ObjectId("5cd29a1c345990cee87fd883")
}
Let's verify our sample data ?
db.exactPositionDemo.find().pretty();
{
"_id": ObjectId("5cd29a1c345990cee87fd883"),
"StudentName": "John",
"StudentScores": [78, 98, 56, 45, 89]
}
Case 1: Get Element at Index 0
Extract the first element (index 0) from StudentScores array ?
db.exactPositionDemo.aggregate([
{
$project: {
"StudentScores": { $slice: ["$StudentScores", 0, 1] }
}
}
]);
{ "_id": ObjectId("5cd29a1c345990cee87fd883"), "StudentScores": [78] }
Case 2: Get Element at Index 1
Extract the second element (index 1) from StudentScores array ?
db.exactPositionDemo.aggregate([
{
$project: {
"StudentScores": { $slice: ["$StudentScores", 1, 1] }
}
}
]);
{ "_id": ObjectId("5cd29a1c345990cee87fd883"), "StudentScores": [98] }
Key Points
-
$slicetakes three parameters: [array, startIndex, numberOfElements] - StartIndex is zero−based (0 = first element, 1 = second element)
- Setting numberOfElements to 1 returns exactly one element at the specified position
- The result is always returned as an array, even for a single element
Conclusion
The $slice operator in aggregation pipelines provides precise control over array element extraction. Use startIndex to specify position and numberOfElements to control how many elements to return from that position.
Advertisements
