How to match and group array elements with the max value in MongoDB aggregation?

MongoDBDatabaseBig Data Analytics

For this, use $group along with $max in MongoDB. Let us create a collection with documents −

> db.demo510.insertOne(
... {
...    details:[
...       {
...          Name:"Chris",
...          Score:56
...       },
...       {
...          Name:"David",
...          Score:45
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8845fa987b6e0e9d18f582")
}
> db.demo510.insertOne(
... {
...    details:[
...       {
...          Name:"Chris",
...          Score:56
...       },
...       {
...          Name:"David",
...          Score:47
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8845fb987b6e0e9d18f583")
}
> db.demo510.insertOne(
... {
...    details:[
...       {
...          Name:"Chris",
...          Score:45
...       },
...       {
...          Name:"David",
...          Score:91
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8845fb987b6e0e9d18f584")
}

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

> db.demo510.find();

This will produce the following output −

{ "_id" : ObjectId("5e8845fa987b6e0e9d18f582"), "details" : [ { "Name" : "Chris", "Score" : 56 },
{ "Name" : "David", "Score" : 45 } ] }
{ "_id" : ObjectId("5e8845fb987b6e0e9d18f583"), "details" : [ { "Name" : "Chris", "Score" : 56 },
{ "Name" : "David", "Score" : 47 } ] }
{ "_id" : ObjectId("5e8845fb987b6e0e9d18f584"), "details" : [ { "Name" : "Chris", "Score" : 45 },
{ "Name" : "David", "Score" : 91 } ] }

Following is the query to match and group array elements with the max value in aggregation −

> db.demo510.aggregate([
... { "$project": {
...    "details": {
...       "$arrayElemAt": [
...          { "$filter": {
...             "input": "$details",
...             "as": "res",
...             "cond": {
...                "$eq": [
...                   "$$res.Score",
...                   { "$max": {
...                      "$map": {
...                         "input": "$details",
...                         "as": "out",
...                         "in": "$$out.Score"
...                      }
...                   }}
...                ]
...             }
...          }},
...          0
...       ]
...    }
... }},
... { "$group": {
...    "_id": "$details.Name",
...    "Name": { "$first": "$details.Name" },
...    "count": { "$sum": 1 }
... }}
... ])

This will produce the following output −

{ "_id" : "David", "Name" : "David", "count" : 1 }
{ "_id" : "Chris", "Name" : "Chris", "count" : 2 }
raja
Published on 13-May-2020 10:23:16
Advertisements