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

MongoDBDatabaseBig Data Analytics

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
}
raja
Published on 14-May-2020 09:39:18
Advertisements