- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Ignore first 4 values in MongoDB documents and display the next 3?
For this, use $slice and set thecount of values to be ignored and displayed. Let us create a collection with documents −
> db.demo693.insertOne({Values:[10,746,736,283,7363,424,3535]}); { "acknowledged" : true, "insertedId" : ObjectId("5ea58a04ece4e5779399c07b") } > db.demo693.insertOne({Values:[100,200,300,100,500,700,900,30000,40003,45999]}); { "acknowledged" : true, "insertedId" : ObjectId("5ea58a1eece4e5779399c07c") }
Display all documents from a collection with the help of find() method −
> db.demo693.find();
This will produce the following output −
{ "_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 ] }
Following is the query to ignore first 4 values in MongoDB documents and display the next 3 using $slice −
> db.demo693.find({},{Values:{$slice:[4,3]}});
This will produce the following output −
{ "_id" : ObjectId("5ea58a04ece4e5779399c07b"), "Values" : [ 7363, 424, 3535 ] } { "_id" : ObjectId("5ea58a1eece4e5779399c07c"), "Values" : [ 500, 700, 900 ] }
Advertisements