Sort and get only the first two fields in a “$group” operation in MongoDB


Let us create a collection with documents −

> db.demo576.insertOne({id:101,Name:"Chris",Marks:45}){
   "acknowledged" : true, "insertedId" : ObjectId("5e916c3b581e9acd78b427fa")
}
> db.demo576.insertOne({id:101,Name:"John",Marks:55}){
   "acknowledged" : true, "insertedId" : ObjectId("5e916c43581e9acd78b427fb")
}
> db.demo576.insertOne({id:101,Name:"John",Marks:65}){
   "acknowledged" : true, "insertedId" : ObjectId("5e916c47581e9acd78b427fc")
}
> db.demo576.insertOne({id:102,Name:"David",Marks:37}){
   "acknowledged" : true, "insertedId" : ObjectId("5e916c55581e9acd78b427fd")
}
> db.demo576.insertOne({id:102,Name:"David",Marks:75}){
   "acknowledged" : true, "insertedId" : ObjectId("5e916c5e581e9acd78b427fe")
}

Display all documents from a collection with the help of find() method −

> db.demo576.find();

This will produce the following output −

{ "_id" : ObjectId("5e916c3b581e9acd78b427fa"), "id" : 101, "Name" : "Chris", "Marks" : 45 }
{ "_id" : ObjectId("5e916c43581e9acd78b427fb"), "id" : 101, "Name" : "John", "Marks" : 55 }
{ "_id" : ObjectId("5e916c47581e9acd78b427fc"), "id" : 101, "Name" : "John", "Marks" : 65 }
{ "_id" : ObjectId("5e916c55581e9acd78b427fd"), "id" : 102, "Name" : "David", "Marks" : 37 }
{ "_id" : ObjectId("5e916c5e581e9acd78b427fe"), "id" : 102, "Name" : "David", "Marks" : 75 }

Following is the query to sort and get only the first two fields in a “$group” operation −

> var query = [
...    {
...       "$sort": { "Marks": 1 }
...    },
...    {
...       "$group": {
...          "_id": "$id",
...          "out": { "$first": "$$ROOT" }
...       }
...    },
...    {
...       "$project": {
...          "_id": "$out._id",
...          "id": "$out.id",
...          "Name": "$out.Name",
...          "MinMarks": "$out.Marks"
...       }
...    }
... ]
> db.demo576.aggregate(query);

This will produce the following output −

{ "_id" : ObjectId("5e916c3b581e9acd78b427fa"), "id" : 101, "Name" : "Chris", "MinMarks" : 45 }
{ "_id" : ObjectId("5e916c55581e9acd78b427fd"), "id" : 102, "Name" : "David", "MinMarks" : 37 }

Updated on: 15-May-2020

253 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements