- 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
MongoDB query to get only a specific number of elements
To return only a specific number of elements, use aggregate() and $slice. Let us create a collection with documents −
> db.demo75.insertOne({"Name":["Sam","Mike","Carol","David","Bob","John"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e2bcd7671bf0181ecc42278") }
Display all documents from a collection with the help of find() method −
> db.demo75.find();
This will produce the following output −
{ "_id" : ObjectId("5e2bcd7671bf0181ecc42278"), "Name" : [ "Sam", "Mike", "Carol", "David", "Bob", "John" ] }
Following is the slice query in MongoDB −
> db.demo75.aggregate([ { $project: { Name: { $slice: [ "$Name", 4 ] } } } ]);
This will produce the following output −
{ "_id" : ObjectId("5e2bcd7671bf0181ecc42278"), "Name" : [ "Sam", "Mike", "Carol", "David" ] }
Advertisements