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

Tìm điểm tối đa cho tên trùng lặp trong MongoDB

Để 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ểmgroup()aggregate $group
Hiệu suấtThấp (JS engine)Cao (native C++)
ShardingKhông hỗ trợHỗ trợ
MemoryGiới hạnCho phép disk spill
Cú phápJS functionDeclarative

Luôn ưu tiên aggregate $group với $max/$min/$sum/$avg cho production.