- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }
Advertisements