- 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
How do you limit an array sub-element in MongoDB?
You can use $slice operator to limit an array. Let us create a collection with documents. Following is the query
> db.limitAnArrayDemo.insertOne( ... { ... _id: 101, ... "PlayerName": "Bob", ... "PlayerDetails": {Age:23,isStudent:true}, ... "PlayerGameScores": [234,5767,58,67,78,90,1002,576,68,45,23,45,678,89,78 ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
Following is the query to display all documents from a collection with the help of find() method
> db.limitAnArrayDemo.find().pretty();
This will produce the following output
{ "_id" : 101, "PlayerName" : "Bob", "PlayerDetails" : { "Age" : 23, "isStudent" : true }, "PlayerGameScores" : [ 234, 5767, 58, 67, 78, 90, 1002, 576, 68, 45, 23, 45, 678, 89, 78 ] }
Following is the query to limit an array sub-element in MongoDB. The below query will display only 10 elements from the last
> db.limitAnArrayDemo.find({}, {PlayerName:1, PlayerDetails: 1, PlayerGameScores:{$slice: -10}}).pretty();
Following is the output displaying 10 PlayerGameScores
{ "_id" : 101, "PlayerName" : "Bob", "PlayerDetails" : { "Age" : 23, "isStudent" : true }, "PlayerGameScores" : [ 90, 1002, 576, 68, 45, 23, 45, 678, 89, 78 ] }
Advertisements