获取集合中每个组具有max属性的MongoDB文档?

您可以使用$sort运算符和$group语句在集合中获取每个组具有max属性的文档。

为了进一步理解该概念,让我们创建一个带有文档的集合。创建带有文档的集合的查询如下-

> db.maxAttributePerGroup.insertOne({"StudentFirstName":"John","StudentLastName":"Smith
   ","StudentAge":29,"StudentId":10});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c76ee341e9c5dd6f1f78277")
}
> db.maxAttributePerGroup.insertOne({"StudentFirstName":"Carol","StudentLastName":"Taylo
   r","StudentAge":19,"StudentId":10});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c76ee4e1e9c5dd6f1f78278")
}
> db.maxAttributePerGroup.insertOne({"StudentFirstName":"Adam","StudentLastName":"Smit
   h","StudentAge":34,"StudentId":20});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c76ee631e9c5dd6f1f78279")
}
> db.maxAttributePerGroup.insertOne({"StudentFirstName":"Bob","StudentLastName":"Taylor"
   ,"StudentAge":58,"StudentId":20});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c76ee791e9c5dd6f1f7827a")
}

find()method的帮助下显示集合中的所有文档。查询如下-

> db.maxAttributePerGroup.find().pretty();

输出结果

{
   "_id" : ObjectId("5c76ee341e9c5dd6f1f78277"),
   "StudentFirstName" : "John",
   "StudentLastName" : "Smith",
   "StudentAge" : 29,
   "StudentId" : 10
}
{
   "_id" : ObjectId("5c76ee4e1e9c5dd6f1f78278"),
   "StudentFirstName" : "Carol",
   "StudentLastName" : "Taylor",
   "StudentAge" : 19,
   "StudentId" : 10
}
{
   "_id" : ObjectId("5c76ee631e9c5dd6f1f78279"),
   "StudentFirstName" : "Adam",
   "StudentLastName" : "Smith",
   "StudentAge" : 34,
   "StudentId" : 20
}
{
   "_id" : ObjectId("5c76ee791e9c5dd6f1f7827a"),
   "StudentFirstName" : "Bob",
   "StudentLastName" : "Taylor",
   "StudentAge" : 58,
   "StudentId" : 20
}

这是获取集合中每个组具有最大属性的文档的查询-

> db.maxAttributePerGroup.aggregate([
   ... {"$sort":{"StudentId":1,"StudentAge":-1}},
   ... {$group:{
   ... "_id":"$StudentId",
   ... "StudentAge":{"$first":"$StudentAge"},
   ... "StudentFirstName":{"$first":"$StudentFirstName"},
   ... "StudentLastName":{"$first":"$StudentLastName"}
... }} ]).pretty();

输出结果

{
   "_id" : 20,
   "StudentAge" : 58,
   "StudentFirstName" : "Bob",
   "StudentLastName" : "Taylor"
}
{
   "_id" : 10,
   "StudentAge" : 29,
   "StudentFirstName" : "John",
   "StudentLastName" : "Smith"
}