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
MongoDB query to get only a specific number of elements
To return only a specific number of elements from an array field in MongoDB, use aggregate() with the $slice operator in a $project stage.
Syntax
db.collection.aggregate([
{
$project: {
fieldName: { $slice: [ "$fieldName", numberOfElements ] }
}
}
]);
Create Sample Data
db.demo75.insertOne({
"Name": ["Sam", "Mike", "Carol", "David", "Bob", "John"]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e2bcd7671bf0181ecc42278")
}
Display all documents from the collection ?
db.demo75.find();
{
"_id": ObjectId("5e2bcd7671bf0181ecc42278"),
"Name": ["Sam", "Mike", "Carol", "David", "Bob", "John"]
}
Example: Get First 4 Elements
Using $slice to return only the first 4 elements from the Name array ?
db.demo75.aggregate([
{
$project: {
Name: { $slice: [ "$Name", 4 ] }
}
}
]);
{
"_id": ObjectId("5e2bcd7671bf0181ecc42278"),
"Name": ["Sam", "Mike", "Carol", "David"]
}
Key Points
- The
$sliceoperator works within the$projectstage of aggregation. - Specify the field name with
"$"prefix and the number of elements to return. - Use positive numbers to get elements from the beginning of the array.
Conclusion
Use aggregate() with $slice in a $project stage to limit array elements returned. This approach is efficient for extracting specific portions of array fields without modifying the original document.
Advertisements
