Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Lấy document có thuộc tính lớn nhất theo nhóm trong MongoDB

Sử dụng $sort kết hợp $group trong Aggregation Framework để lấy document có giá trị lớn nhất theo từng nhóm.

Ví dụ minh họa

Tạo collection maxAttributePerGroup:

> db.maxAttributePerGroup.insertOne({"HoSinhVien": "John", "TenDem": "Smith", "TuoiSinhVien": 29, "MaSinhVien": 10});
> db.maxAttributePerGroup.insertOne({"HoSinhVien": "Carol", "TenDem": "Taylor", "TuoiSinhVien": 19, "MaSinhVien": 10});
> db.maxAttributePerGroup.insertOne({"HoSinhVien": "Adam", "TenDem": "Smith", "TuoiSinhVien": 34, "MaSinhVien": 20});
> db.maxAttributePerGroup.insertOne({"HoSinhVien": "Bob", "TenDem": "Taylor", "TuoiSinhVien": 58, "MaSinhVien": 20});

Dữ liệu: Hai nhóm MaSinhVien (10 và 20), mỗi nhóm 2 sinh viên.

Truy vấn aggregation

> db.maxAttributePerGroup.aggregate([
  {$sort: {"MaSinhVien": 1, "TuoiSinhVien": -1}},
  {$group: {
    _id: "$MaSinhVien",
    TuoiSinhVien: {$first: "$TuoiSinhVien"},
    HoSinhVien: {$first: "$HoSinhVien"},
    TenDem: {$first: "$TenDem"}
  }}
]).pretty();

Kết quả - Sinh viên lớn tuổi nhất mỗi nhóm:

{ "_id": 20, "TuoiSinhVien": 58, "HoSinhVien": "Bob", "TenDem": "Taylor" }
{ "_id": 10, "TuoiSinhVien": 29, "HoSinhVien": "John", "TenDem": "Smith" }

Cơ chế: $sort sắp xếp trước (theo nhóm tăng, tuổi giảm), $group lấy document đầu tiên ($first) của mỗi nhóm - chính là document có tuổi lớn nhất.