Bạn có thể nhận các tài liệu có thuộc tính tối đa cho mỗi nhóm trong một bộ sưu tập bằng cách sử dụng toán tử $ sort cùng với câu lệnh $ group.
Để hiểu thêm về khái niệm, chúng ta hãy tạo một bộ sưu tập với tài liệu. Truy vấn để tạo một bộ sưu tập với tài liệu như sau -
> 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")
} Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find (). Truy vấn như sau -
> db.maxAttributePerGroup.find().pretty();
Đầu ra
{
"_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
} Đây là truy vấn để lấy tài liệu có thuộc tính tối đa cho mỗi nhóm trong một bộ sưu tập -
> db.maxAttributePerGroup.aggregate([
... {"$sort":{"StudentId":1,"StudentAge":-1}},
... {$group:{
... "_id":"$StudentId",
... "StudentAge":{"$first":"$StudentAge"},
... "StudentFirstName":{"$first":"$StudentFirstName"},
... "StudentLastName":{"$first":"$StudentLastName"}
... }} ]).pretty(); Đầu ra
{
"_id" : 20,
"StudentAge" : 58,
"StudentFirstName" : "Bob",
"StudentLastName" : "Taylor"
}
{
"_id" : 10,
"StudentAge" : 29,
"StudentFirstName" : "John",
"StudentLastName" : "Smith"
}