- 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
Limit number of values in a field with MongoDB?
To limit the number of values in a field, use MongoDB $slice. Let us create a collection with documents −
> db.demo173.insertOne({"ListOfValues":[10,40,100,560,700,900]}); { "acknowledged" : true, "insertedId" : ObjectId("5e383a4f9e4f06af551997e4") }
Display all documents from a collection with the help of find() method −
> db.demo173.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e383a4f9e4f06af551997e4"), "ListOfValues" : [10, 40, 100, 560, 700, 900 ] }
Following is the query to limit number of values in a field using MongoDB −
> db.demo173.find({}, { "ListOfValues": { "$slice": -2 } } );
This will produce the following output −
{ "_id" : ObjectId("5e383a4f9e4f06af551997e4"), "ListOfValues" : [ 700, 900 ] }
Advertisements