- 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 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 } ] }
Advertisements