
- 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
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 ] }
- Related Questions & Answers
- Limit number of values in a field with MongoDB?
- MongoDB query to limit the returning values of a field?
- Limit the number of documents in a collection in MongoDB?
- List all values of a certain field in MongoDB?
- Get the duplicate values of a field in MongoDB?
- How to limit the amount of characters returned from a field in a MongoDB?
- MongoDB Aggregate to limit the number of records
- How to count number of distinct values per field/ key in MongoDB?
- How to limit the amount of characters returned from a field in a MongoDB query?
- Update MongoDB field using value of another field?
- Fetch specific field values in MongoDB
- Find all the non-distinct values of a field in MongoDB?
- Get a count of total documents with MongoDB while using limit?
- How to compare field values in MongoDB?
- How to limit the number of records, while retrieving data from a MongoDB collection using Java?
Advertisements