Để tìm giá trị lớn nhất theo nhóm (group by), dùng phương thức group() (legacy shell helper) hoặc aggregate $group (chuẩn, khuyến nghị).
Dữ liệu mẫu
> db.demo114.insertOne({"Score":60,"Name":"Chris"});
> db.demo114.insertOne({"Score":87,"Name":"Chris"});
> db.demo114.insertOne({"Score":45,"Name":"David"});
> db.demo114.insertOne({"Score":67,"Name":"Chris"});
> db.demo114.insertOne({"Score":38,"Name":"David"});
Cách 1: group() legacy (shell helper)
> db.demo114.group(
{ key: {Name:true},
reduce: function(c,p) {
if (p.maximumScore < c.Score) { p.maximumScore = c.Score; }
},
initial: { maximumScore: 0 }
}
);
Cách 2: Aggregate $group (khuyến nghị, chuẩn)
> db.demo114.aggregate([
{ $group: {
_id: "$Name",
maximumScore: { $max: "$Score" }
}}
]);
Kết quả (cả hai)
[ { "Name" : "Chris", "maximumScore" : 87 }, { "Name" : "David", "maximumScore" : 45 } ]
So sánh:
| Đặc điểm | group() | aggregate $group |
|---|---|---|
| Hiệu suất | Thấp (JS engine) | Cao (native C++) |
| Sharding | Không hỗ trợ | Hỗ trợ |
| Memory | Giới hạn | Cho phép disk spill |
| Cú pháp | JS function | Declarative |
Luôn ưu tiên aggregate $group với $max/$min/$sum/$avg cho production.