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 slice only one element of array
To slice only one element of an array in MongoDB, use the $slice operator in the projection stage of a query. This operator allows you to return a specific number of array elements from the beginning or end of an array.
Syntax
db.collection.find(
{},
{ "arrayField": { $slice: N } }
);
Where N is the number of elements to return (positive for first N elements, negative for last N elements).
Sample Data
db.demo579.insertOne({
"_id": 101,
"details": { "FirstName": "John" },
"Marks": [ 56, 78, 90, 34, 45, 74 ]
});
{ "acknowledged": true, "insertedId": 101 }
Example: Slice First Element
To get only the first element from the Marks array ?
db.demo579.find(
{},
{
"Marks": { $slice: 1 },
"details": 0,
"_id": 0
}
);
{ "Marks": [ 56 ] }
Example: Slice Last Element
To get only the last element from the array ?
db.demo579.find(
{},
{
"Marks": { $slice: -1 },
"details": 0,
"_id": 0
}
);
{ "Marks": [ 74 ] }
Key Points
-
$slice: 1returns the first element of the array. -
$slice: -1returns the last element of the array. - Use
0in projection to exclude unwanted fields from the result.
Conclusion
The $slice operator provides an efficient way to return specific portions of arrays in MongoDB queries. Use positive values for elements from the beginning and negative values for elements from the end.
Advertisements
