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
Count number of documents from MongoDB collection inside Array?
To count the number of documents from the collection inside the array, use aggregate(). Let us create a collection with documents −
> db.demo332.insertOne({details:[{Name:"Chris",Age:21}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e521f16f8647eb59e56208e")
}
> db.demo332.insertOne({details:[{Name:"David",Age:23},{Name:"Bob",Age:22}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e521f21f8647eb59e56208f")
}
Display all documents from a collection with the help of find() method −
> db.demo332.find();
This will produce the following output −
{ "_id" : ObjectId("5e521f16f8647eb59e56208e"), "details" : [ { "Name" : "Chris", "Age" : 21 } ] }
{ "_id" : ObjectId("5e521f21f8647eb59e56208f"), "details" : [ { "Name" : "David", "Age" : 23 }, { "Name" : "Bob", "Age" : 22 } ] }
Following is the query to count the number of documents from the collection inside an array −
> db.demo332.aggregate([
... {
... $project: {
... numberOfDocuments: { $cond: { if: { $isArray: "$details" }, then: { $size: "$details" }, else: "No Documents"} }
... }
... }
... ] )
This will produce the following output −
{ "_id" : ObjectId("5e521f16f8647eb59e56208e"), "numberOfDocuments" : 1 }
{ "_id" : ObjectId("5e521f21f8647eb59e56208f"), "numberOfDocuments" : 2 }Advertisements