
- MongoDB Tutorial
- MongoDB - Home
- MongoDB - Overview
- MongoDB - Advantages
- MongoDB - Environment
- MongoDB - Data Modeling
- MongoDB - Create Database
- MongoDB - Drop Database
- MongoDB - Create Collection
- MongoDB - Drop Collection
- MongoDB - Data Types
- MongoDB - Insert Document
- MongoDB - Query Document
- MongoDB - Update Document
- MongoDB - Delete Document
- MongoDB - Projection
- MongoDB - Limiting Records
- MongoDB - Sorting Records
- MongoDB - Indexing
- MongoDB - Aggregation
- MongoDB - Replication
- MongoDB - Sharding
- MongoDB - Create Backup
- MongoDB - Deployment
- MongoDB - Java
- MongoDB - PHP
- Advanced MongoDB
- MongoDB - Relationships
- MongoDB - Database References
- MongoDB - Covered Queries
- MongoDB - Analyzing Queries
- MongoDB - Atomic Operations
- MongoDB - Advanced Indexing
- MongoDB - Indexing Limitations
- MongoDB - ObjectId
- MongoDB - Map Reduce
- MongoDB - Text Search
- MongoDB - Regular Expression
- Working with Rockmongo
- MongoDB - GridFS
- MongoDB - Capped Collections
- Auto-Increment Sequence
- MongoDB Useful Resources
- MongoDB - Questions and Answers
- MongoDB - Quick Guide
- MongoDB - Useful Resources
- MongoDB - Discussion
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" ] }
- Related Articles
- MongoDB query to get a specific number of items
- MongoDB query to get only specific fields in nested array documents?
- MongoDB query to get only distinct values
- MongoDB Query to search for records only in a specific hour?
- How to run MongoDB query to update only a specific field value?
- MongoDB query to get specific month|year (not date)?
- Get only the FALSE value with MongoDB query
- MongoDB query select and display only a specific field from the document?
- MongoDB query to 'sort' and display a specific number of values
- Get specific elements from embedded array in MongoDB?
- MongoDB query to remove a specific document
- Get count of array elements from a specific field in MongoDB documents?
- MongoDB query to return only specific fields (phone numbers) in the form of an array?
- MongoDB query to sum specific fields
- MongoDB query to get record beginning with specific element from an array?

Advertisements