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 }
Updated on: 2020-04-02T06:47:55+05:30

202 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements