
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Group with Multiple Fields and Count Duplicate Values in MongoDB
For this, use MongoDB aggregate and within that, use $cond. The $cond evaluates a boolean expression to return one of the two specified return expressions.
Let us first create a collection with documents −
> db.demo536.insertOne({"Name1":"Chris","Name2":"David"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8c843eef4dcbee04fbbc01") } > db.demo536.insertOne({"Name1":"David","Name2":"Chris"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8c843fef4dcbee04fbbc02") } > db.demo536.insertOne({"Name1":"Bob","Name2":"Sam"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8c843fef4dcbee04fbbc03") } > db.demo536.insertOne({"Name1":"Chris","Name2":"David"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8c843fef4dcbee04fbbc04") }
Display all documents from a collection with the help of find() method −
> db.demo536.find();
This will produce the following output −
{ "_id" : ObjectId("5e8c843eef4dcbee04fbbc01"), "Name1" : "Chris", "Name2" : "David" } { "_id" : ObjectId("5e8c843fef4dcbee04fbbc02"), "Name1" : "David", "Name2" : "Chris" } { "_id" : ObjectId("5e8c843fef4dcbee04fbbc03"), "Name1" : "Bob", "Name2" : "Sam" } { "_id" : ObjectId("5e8c843fef4dcbee04fbbc04"), "Name1" : "Chris", "Name2" : "David" }
Following is the query to group with multiple fields −
> db.demo536.aggregate([ ... { ... $project: ... { ... FirstName1: ... { ... $cond: { if: { $gte: [ "$Name1", "$Name2" ] }, then: "$Name2", else: "$Name1" } ... }, ... FirstName2: ... { ... $cond: { if: { $lt: [ "$Name1", "$Name2" ] }, then: "$Name2", else: "$Name1" } ... } ... } ... } ... ,{ ... $group: ... { ... _id: ... { ... Name1: "$FirstName1", ... Name2: "$FirstName2" ... } ... ,count: { $sum: 1} ... } ... } ... ])
This will produce the following output &imnus;
{ "_id" : { "Name1" : "Bob", "Name2" : "Sam" }, "count" : 1 } { "_id" : { "Name1" : "Chris", "Name2" : "David" }, "count" : 3 }
Advertisements