
- 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 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 ] }
- Related Questions & Answers
- Limit number of values in a field using MongoDB?
- MongoDB query to limit the returning values of a field?
- Limit the number of documents in a collection in MongoDB?
- Update all the values of a field with a specific string 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 query MongoDB with a LIMIT?
- How to limit the values in a Number JSpinner Component with Java?
- How to limit the amount of characters returned from a field in a MongoDB query?
- Fetch specific field values in MongoDB
- Display the last two values from field with MongoDB
- Find all the non-distinct values of a field in MongoDB?
Advertisements