MongoDB query to count the number of array items in documents and display in a new field



To count the number of array items in a document, use $size in MongoDB. Let us create a collection with documents −

> db.demo703.insertOne({"ListOfSubject":["MySQL","MongoDB"]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ea6ebaf551299a9f98c93b4") } > db.demo703.insertOne({"ListOfSubject":["Java"]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ea6ebb5551299a9f98c93b5") } > db.demo703.insertOne({"ListOfSubject":["C","C++","Python"]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ea6ebbf551299a9f98c93b6") }

Display all documents from a collection with the help of find() method −

> db.demo703.find();

This will produce the following output −

{ "_id" : ObjectId("5ea6ebaf551299a9f98c93b4"), "ListOfSubject" : [ "MySQL", "MongoDB" ] } { "_id" : ObjectId("5ea6ebb5551299a9f98c93b5"), "ListOfSubject" : [ "Java" ] } { "_id" : ObjectId("5ea6ebbf551299a9f98c93b6"), "ListOfSubject" : [ "C", "C++", "Python" ] }

Following is the query to count the number of array items −

>db.demo703.aggregate({$project:{NumberOfItemsInEachArray:{$size:"$ListOfSubject"}}}).pretty();

This will produce the following output −

{    "_id" : ObjectId("5ea6ebaf551299a9f98c93b4"),    "NumberOfItemsInEachArray" : 2 } {    "_id" : ObjectId("5ea6ebb5551299a9f98c93b5"),    "NumberOfItemsInEachArray" : 1 } {    "_id" : ObjectId("5ea6ebbf551299a9f98c93b6"),    "NumberOfItemsInEachArray" : 3 }
Updated on: 2020-05-14T09:39:38+05:30

152 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements