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

Cách truy vấn top N dòng trong MongoDB?

Để truy vấn top N dòng trong MongoDB, bạn sử dụng Aggregation Framework với các stage $sort, $limit và $match.

Tạo dữ liệu mẫu

> db.topNRowsDemo.insertOne({"StudentName":"Larry","Score":78});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca26eee6304881c5ce84b91") }
> db.topNRowsDemo.insertOne({"StudentName":"Chris","Score":45});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca26ef66304881c5ce84b92") }
> db.topNRowsDemo.insertOne({"StudentName":"Mike","Score":65});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca26efe6304881c5ce84b93") }
> db.topNRowsDemo.insertOne({"StudentName":"Adam","Score":55});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca26f066304881c5ce84b94") }
> db.topNRowsDemo.insertOne({"StudentName":"John","Score":86});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca26f0f6304881c5ce84b95") }

Hiển thị tất cả:

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

Truy vấn Top N với Aggregation

Ví dụ: Lấy top 5 sinh viên có Score > 65, sắp xếp theo tên:

> db.topNRowsDemo.aggregate([ 
  {$sort: {StudentName: 1}}, 
  {$limit: 5}, 
  {$match: {Score: {$gt: 65}}} 
]).pretty();

Kết quả:


Thứ tự stage quan trọng:

  1. $sort trước - sắp xếp dữ liệu
  2. $limit - giới hạn số lượng document
  3. $match - lọc điều kiện (nên đặt trước $sort/$limit để tối ưu hiệu năng)

Best practice: Đặt $match ở đầu pipeline để giảm lượng dữ liệu cần xử lý các stage sau, tận dụng index nếu có.