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
Display the last two values from field with MongoDB
To display the last two values from a field in MongoDB, use the $slice operator with a negative value in the projection. The negative value indicates retrieving elements from the end of the array.
Syntax
db.collection.find({}, { "fieldName": { "$slice": -N } });
Sample Data
Let us first create a collection with documents ?
db.numberOfValuesDemo.insertOne({
"Values": [100, 200, 300, 900, 1000, 98]
});
{
"acknowledged": true,
"insertedId": ObjectId("5cefb736ef71edecf6a1f6ab")
}
Display all documents from a collection with the help of find() method ?
db.numberOfValuesDemo.find().pretty();
{
"_id": ObjectId("5cefb736ef71edecf6a1f6ab"),
"Values": [
100,
200,
300,
900,
1000,
98
]
}
Example: Get Last Two Values
Following is the query to get the last two values. Here, we have used negative sign with $slice ?
db.numberOfValuesDemo.find({}, { "Values": { "$slice": -2 } });
{ "_id": ObjectId("5cefb736ef71edecf6a1f6ab"), "Values": [1000, 98] }
Key Points
-
$slice: -2returns the last 2 elements from the array. - Positive values with
$slicereturn elements from the beginning of the array. - The projection only affects the returned document structure, not the stored data.
Conclusion
Use $slice with negative values in MongoDB projections to retrieve the last N elements from an array field. This is particularly useful for getting recent entries or the latest values from array fields.
Advertisements
