How can I count the documents in an array based on the value of a specific field?


For such match and count, use $match in MongoDB. Let us create a collection with documents −

> db.demo726.insertOne(
...    {
...       id:101,
...       "details": [
...          {
...             Name:"Chris"
...
...          },
...          {
...             Name:"Chris"
...
...          },
...          {
...             Name:"Bob"
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eab318643417811278f5894")
}

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

> db.demo726.find();

This will produce the following output −

{ "_id" : ObjectId("5eab318643417811278f5894"), "id" : 101, "details" : [ { "Name" : "Chris" }, { "Name" : "Chris" }, { "Name" : "Bob" } ] }

Following is the query to count the documents in an array based in the value of a specific field in MongoDB −

> db.demo726.aggregate([
...
...    { $unwind: '$details' },
...
...    { $match: { 'details.Name': "Chris"} },
...       { $group: {
...          _id: "$Name",
...          Total_Value: { $sum: 1 }
...       }
...    }
... ]);

This will produce the following output −

{ "_id" : null, "Total_Value" : 2 }

Updated on: 15-May-2020

97 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements