- 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 using MongoDB?
To limit number of values in a field, use $slice operator.
Let us first create a collection with documents −
> db.numberOfValuesDemo.insertOne({"Values":[100,200,300,900,1000,98]}); { "acknowledged" : true, "insertedId" : ObjectId("5cefb736ef71edecf6a1f6ab") }
Display all documents from a collection with the help of find() method −
> db.numberOfValuesDemo.find().pretty();
Output
{ "_id" : ObjectId("5cefb736ef71edecf6a1f6ab"), "Values" : [ 100, 200, 300, 900, 1000, 98 ] }
Following is the query to limit number of values in a field using MongoDB −
> db.numberOfValuesDemo.find({},{ "Values": { "$slice": 2 } } );
Output
{ "_id" : ObjectId("5cefb736ef71edecf6a1f6ab"), "Values" : [ 100, 200 ] }
Advertisements