
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
MongoDB query to limit the returning values of a field?
For this, use $slice. Let us create a collection with documents −
> db.demo594.insertOne( ... { ... id:1, ... details:[ ... {Name:"Chris",Age:21}, ... {Name:"Bob",Age:20}, ... {Name:"David",Age:23}, ... {Name:"Sam",Age:22} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e933459fd2d90c177b5bcdd") }
Display all documents from a collection with the help of find() method −
> db.demo594.find();
This will produce the following output −
{ "_id" : ObjectId("5e933459fd2d90c177b5bcdd"), "id" : 1, "details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "Bob", "Age" : 20 }, { "Name" : "David", "Age" : 23 }, { "Name" : "Sam", "Age" : 22 } ] }
Following is the query to limit the returning values of a field −
> db.demo594.find({}, {"Name": 1, "details": { "$slice": 1}});
This will produce the following output −
{ "_id" : ObjectId("5e933459fd2d90c177b5bcdd"), "details" : [ { "Name" : "Chris", "Age" : 21 } ] }
- Related Questions & Answers
- Limit number of values in a field using MongoDB?
- Limit number of values in a field with MongoDB?
- How to limit the amount of characters returned from a field in a MongoDB query?
- MongoDB query to add up the values of a specific field in documents
- How to query MongoDB with a LIMIT?
- How to limit the amount of characters returned from a field in a MongoDB?
- MongoDB query to insert but limit the total records
- Get the duplicate values of a field in MongoDB?
- MongoDB query for a single field
- In MongoDB will limit() increase query speed?
- MongoDB query by sub-field?
- MongoDB query to limit subdocuments having the given fields of the 'projection'
- MongoDB query to search for string like “@email” in the field values
- MongoDB query to collectively match intersection of documents against a field
- Find all the non-distinct values of a field in MongoDB?
Advertisements