- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
MongoDB aggregate $slice to get the length of the array
For this, use $project and in that, $size to get the length. Let us first create a collection with documents −
> db.demo382.insertOne( ... { ... ... "Name" : "David", ... "details" : [ ... { ... "SubjectName":"MySQL" ... }, ... { ... "SubjectName":"MongoDB" ... }, ... { ... "SubjectName":"Java" ... } ... ] ... ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5b5e1c22064be7ab44e7f0") }
Display all documents from a collection with the help of find() method &Minus;
> db.demo382.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e5b5e1c22064be7ab44e7f0"), "Name" : "David", "details" : [ { "SubjectName" : "MySQL" }, { "SubjectName" : "MongoDB" }, { "SubjectName" : "Java" } ] }
Following is the query to aggregate $slice and get the length −
> db.demo382.aggregate([ ... { "$match": { "Name": "David" } }, ... { "$project": { "count": { "$size": "$details" }}} ... ])
This will produce the following output −
{ "_id" : ObjectId("5e5b5e1c22064be7ab44e7f0"), "count" : 3 }
- Related Articles
- Aggregate a $slice to get an element in exact position from a nested array in MongoDB?
- MongoDB Aggregate to get average from document and of array elements?
- How to use $slice operator to get last element of array in MongoDB?
- MongoDB Aggregation to slice array inside array
- Get the first element in an array and return using MongoDB Aggregate?
- Get the average of marks in MongoDB with aggregate?
- MongoDB query to aggregate nested array
- Get substring in MongoDB aggregate
- Using MongoDB Aggregate and GroupBy to get the frequency of name record
- MongoDB query to slice only one element of array
- How to aggregate sum in MongoDB to get the total count?
- Get the length of distinct values in an array with MongoDB
- MongoDB aggregate to get the count of field values of corresponding duplicate names?
- How to aggregate array documents in MongoDB?
- MongoDB slice array in populated field?

Advertisements