Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Set MongoDB $slice with a range?
To set slice along with a range, use the $slice operator with parameters. These parameters are to be set for beginning position of the elements to be fetched and the 2nd parameter is for range. Let us create a collection with documents −
> db.demo54.insertOne({"ListOfValues":[100,2030,5353,7364,635,535,524,423,2434,1323,799874,90]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e27151ecfb11e5c34d89914")
}
Display all documents from a collection with the help of find() method −
> db.demo54.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e27151ecfb11e5c34d89914"),
"ListOfValues" : [
100,
2030,
5353,
7364,
635,
535,
524,
423,
2434,
1323,
799874,
90
]
}
Following is the query to set slice with a range −
> db.demo54.find({}, { "ListOfValues": { $slice: [5,3]}}).pretty();
This will produce the following output −
{
"_id" : ObjectId("5e27151ecfb11e5c34d89914"),
"ListOfValues" : [
535,
524,
423
]
}Advertisements