 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
MongoDB query for counting number of unique fields grouped by another field?
For this, use aggregate() and group with $group. Let us create a collection with documents −
> db.demo354.insertOne({"Name1":"Chris","Name2":"David"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e5685a6f8647eb59e5620c0") } > db.demo354.insertOne({"Name1":"Chris","Name2":"David"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e5685a9f8647eb59e5620c1") } > db.demo354.insertOne({"Name1":"Chris","Name2":"Bob"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e5685aff8647eb59e5620c2") } > db.demo354.insertOne({"Name1":"Carol","Name2":"John"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e5685c4f8647eb59e5620c3") } > db.demo354.insertOne({"Name1":"Carol","Name2":"John"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e5685c5f8647eb59e5620c4") } Display all documents from a collection with the help of find() method −
> db.demo354.find();
This will produce the following output −
{ "_id" : ObjectId("5e5685a6f8647eb59e5620c0"), "Name1" : "Chris", "Name2" : "David" } { "_id" : ObjectId("5e5685a9f8647eb59e5620c1"), "Name1" : "Chris", "Name2" : "David" } { "_id" : ObjectId("5e5685aff8647eb59e5620c2"), "Name1" : "Chris", "Name2" : "Bob" } { "_id" : ObjectId("5e5685c4f8647eb59e5620c3"), "Name1" : "Carol", "Name2" : "John" } { "_id" : ObjectId("5e5685c5f8647eb59e5620c4"), "Name1" : "Carol", "Name2" : "John" } Following is the query for counting number of unique fields grouped by another field −
> db.demo354.aggregate([ ... { ...    $group: { ...       _id: { ...          "Name1": "$Name1", ...          "Name2": "$Name2" ...       }, ...    } ... }, ... { ...    $group: { ...       _id: "$_id.Name1", ...       "Name2": { $sum: 1 } ...    } ... }, ... { ...    $project: { ...       _id: 0, ...       Name1: "$_id", ...       Name2: 1 ...    } ... } ... ]) This will produce the following output −
{ "Name2" : 2, "Name1" : "Chris" } { "Name2" : 1, "Name1" : "Carol" }Advertisements
 