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 Limit fields and slice projection together?
To limit fields and use slice projection together in MongoDB, use the $slice operator within the projection parameter of the find() method. This allows you to control which fields are returned while simultaneously limiting array elements using slice.
Syntax
db.collection.find(
{ query },
{
"field1": 0,
"field2": 0,
"arrayField": { "$slice": [startIndex, count] }
}
);
Sample Data
db.limitAndSliceProjectionDemo.insertOne({
"_id": 101,
"UserName": "Carol",
"UserAge": 26,
"UserMessage": [
"Hi",
"Hello",
"Bye",
"Awesome",
"Good",
"Bad",
"Nice",
"Good Night",
"Good Morning"
]
});
{ "acknowledged": true, "insertedId": 101 }
Example: Limit Fields and Slice Array
Query to exclude specific fields and slice array from index 2 to get 4 elements ?
db.limitAndSliceProjectionDemo.find(
{ "UserName": "Carol" },
{
"_id": 0,
"UserName": 0,
"UserAge": 0,
"UserMessage": { "$slice": [2, 4] }
}
);
{ "UserMessage": [ "Bye", "Awesome", "Good", "Bad" ] }
Key Points
-
$slice: [2, 4]starts at index 2 and returns 4 elements. - Setting field values to
0excludes them from the result. - The
$sliceoperator works within the projection stage to limit array elements.
Conclusion
Combine field limiting with $slice projection to control both which fields are returned and how many array elements are included. This provides precise control over query output structure and size.
Advertisements
