如何在MongoDB聚合中将数组元素与最大值匹配和分组?

为此,在MongoDB中将$group和$max一起使用。让我们创建一个包含文档的集合-

> 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")
}

find()方法的帮助下显示集合中的所有文档-

> db.demo510.find();

这将产生以下输出-

{ "_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 } ] }

以下是查询以聚合中的最大值匹配和分组数组元素-

> 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 }
... }}
... ])

这将产生以下输出-

{ "_id" : "David", "Name" : "David", "count" : 1 }
{ "_id" : "Chris", "Name" : "Chris", "count" : 2 }