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
How to get max values for distinct elements in MongoDB
To get max values for distinct elements, use $sort and $group in MongoDB aggregate(). Let us create a collection with documents −
> db.demo750.insertOne({id:101,value:50});
{
"acknowledged" : true,
"insertedId" : ObjectId("5eae74b2a930c785c834e566")
}
> db.demo750.insertOne({id:102,value:40});
{
"acknowledged" : true,
"insertedId" : ObjectId("5eae74c8a930c785c834e567")
}
> db.demo750.insertOne({id:101,value:110});
{
"acknowledged" : true,
"insertedId" : ObjectId("5eae74dba930c785c834e568")
}
Display all documents from a collection with the help of find() method −
> db.demo750.find();
This will produce the following output −
{ "_id" : ObjectId("5eae74b2a930c785c834e566"), "id" : 101, "value" : 50 }
{ "_id" : ObjectId("5eae74c8a930c785c834e567"), "id" : 102, "value" : 40 }
{ "_id" : ObjectId("5eae74dba930c785c834e568"), "id" : 101, "value" : 110 }
Following is the query to get max values for distinct elements in MongoDB −
> db.demo750.aggregate([
... {
... $sort: { value: -1 }
... },
... {
... $group: {
... _id: "$id",
... value: { $first: "$value" }
... }
... },
... {
... $project: {
... id: "$_id",
... value: 1
... }
... }
... ])
This will produce the following output −
{ "_id" : 102, "value" : 40, "id" : 102 }
{ "_id" : 101, "value" : 110, "id" : 101 }Advertisements