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

Đếm tổng document trong MongoDB khi dùng limit

Sử dụng toán tử $facet trong Aggregation Framework để đồng thời lấy dữ liệu phân trang và đếm tổng số document.

Ví dụ minh họa

Tạo collection totalDocumentDemo:

> db.totalDocumentDemo.insertOne({"MaGiangVien": 100, "TenGiangVien": "Larry", "MonYeuThich": ["Java", "MongoDB", "Python"]});
> db.totalDocumentDemo.insertOne({"MaGiangVien": 200, "TenGiangVien": "Sam", "MonYeuThich": ["SQL Server", "C#", "Javascript"]});

Truy vấn $facet

> db.totalDocumentDemo.aggregate([
  {$facet: {
    TatCaDuLieu: [{$match: {}}],
    TongSoDocument: [{$count: "tongSoDocument"}]
  }}
]).pretty();

Kết quả:

{
  "TatCaDuLieu": [
    { "_id": ObjectId("..."), "MaGiangVien": 100, "TenGiangVien": "Larry", "MonYeuThich": ["Java", "MongoDB", "Python"] },
    { "_id": ObjectId("..."), "MaGiangVien": 200, "TenGiangVien": "Sam", "MonYeuThich": ["SQL Server", "C#", "Javascript"] }
  ],
  "TongSoDocument": [{ "tongSoDocument": 2 }]
}

Ứng dụng: Rất hữu ích cho phân trang (pagination) - lấy một trang dữ liệu và biết tổng số record để tính tổng số trang.