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