
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 }
- Related Questions & Answers
- How can I find documents in MongoDB based on the number of matched objects within an array?
- Get count of array elements from a specific field in MongoDB documents?
- Count the documents with a field value beginning with 13
- MongoDB query to get specific list of names from documents where the value of a field is an array
- How can I use MongoDB to find all documents which have a field, regardless of the value of that field?
- How to filter documents based on an array in MongoDB?
- Find MongoDB documents where elements of an array have a specific value?
- How do you convert an array of ObjectIds into an array of embedded documents with a field containing the original array element value?
- How can I rename a field for all documents in MongoDB?
- How to search for documents based on the value of adding two properties in MongoDB?
- MongoDB aggregation to fetch documents with specific field value?
- Find documents where all elements of an array have a specific value in MongoDB?
- How to sum based on field value in MySQL?
- Aggregate based on array value to sum values in different MongoDB documents?
- Querying on an array of objects for specific nested documents with MongoDB?
Advertisements