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
Ignore first 4 values in MongoDB documents and display the next 3?
To ignore the first 4 values in MongoDB documents and display the next 3, use the $slice operator with [skip, limit] array notation in the projection stage.
Syntax
db.collection.find(
{},
{ arrayField: { $slice: [skipCount, limitCount] } }
);
Sample Data
db.demo693.insertMany([
{ Values: [10, 746, 736, 283, 7363, 424, 3535] },
{ Values: [100, 200, 300, 100, 500, 700, 900, 30000, 40003, 45999] }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ea58a04ece4e5779399c07b"),
ObjectId("5ea58a1eece4e5779399c07c")
]
}
Display all documents to see the complete data ?
db.demo693.find();
{ "_id": ObjectId("5ea58a04ece4e5779399c07b"), "Values": [10, 746, 736, 283, 7363, 424, 3535] }
{ "_id": ObjectId("5ea58a1eece4e5779399c07c"), "Values": [100, 200, 300, 100, 500, 700, 900, 30000, 40003, 45999] }
Example: Skip First 4, Show Next 3
Use $slice: [4, 3] to skip the first 4 elements and return the next 3 ?
db.demo693.find(
{},
{ Values: { $slice: [4, 3] } }
);
{ "_id": ObjectId("5ea58a04ece4e5779399c07b"), "Values": [7363, 424, 3535] }
{ "_id": ObjectId("5ea58a1eece4e5779399c07c"), "Values": [500, 700, 900] }
How It Works
-
[4, 3]means skip 4 elements from the beginning, then return 3 elements - First document: skips [10, 746, 736, 283], returns [7363, 424, 3535]
- Second document: skips [100, 200, 300, 100], returns [500, 700, 900]
Conclusion
The $slice operator with [skip, limit] notation efficiently extracts specific array segments. Use [4, 3] to skip the first 4 elements and display the next 3 in MongoDB documents.
Advertisements
