Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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 }Advertisements