Sử dụng distinct() kết hợp .length để đếm số giá trị duy nhất của một trường.
Ví dụ minh họa
Tạo collection distinctCountValuesDemo:
> db.distinctCountValuesDemo.insertOne({"TenSinhVien": "John", "MonYeuThich": ["C", "C++", "Java", "MySQL", "C", "C++"]});
> db.distinctCountValuesDemo.insertOne({"TenSinhVien": "Larry", "MonYeuThich": ["MongoDB", "SQL Server"]});
Lấy giá trị distinct
> db.distinctCountValuesDemo.distinct('MonYeuThich');
["C", "C++", "Java", "MySQL", "MongoDB", "SQL Server"]
Đếm số lượng
> db.distinctCountValuesDemo.distinct('MonYeuThich').length;
6
Lưu ý: distinct() trả về mảng, .length là property của JavaScript array. Cách này load toàn bộ giá trị distinct vào bộ nhớ - cẩn thận với cardinality cao.
Thay thế cho dữ liệu lớn: Dùng aggregation $group + $sum hoặc $addToSet + $size để xử lý server-side.