Sử dụng distinct() lấy mảng giá trị duy nhất, sau đó lấy .length.
db.yourCollectionName.distinct('yourFieldName').length;
Tạo collection
> db.countOrSizeDemo.insertOne({"StudentFirstName": "John"});
{ "acknowledged": true, "insertedId": ObjectId("5cd304f5b64f4b851c3a13dc") }
> db.countOrSizeDemo.insertOne({"StudentFirstName": "David"});
{ "acknowledged": true, "insertedId": ObjectId("5cd304fab64f4b851c3a13dd") }
> db.countOrSizeDemo.insertOne({"StudentFirstName": "David"});
{ "acknowledged": true, "insertedId": ObjectId("5cd304fcb64f4b851c3a13de") }
> db.countOrSizeDemo.insertOne({"StudentFirstName": "Carol"});
{ "acknowledged": true, "insertedId": ObjectId("5cd30500b64f4b851c3a13df") }
> db.countOrSizeDemo.insertOne({"StudentFirstName": "Sam"});
{ "acknowledged": true, "insertedId": ObjectId("5cd30505b64f4b851c3a13e0") }
> db.countOrSizeDemo.insertOne({"StudentFirstName": "John"});
{ "acknowledged": true, "insertedId": ObjectId("5cd3050ab64f4b851c3a13e1") }
Hiển thị tất cả
> db.countOrSizeDemo.find();
Đếm số tên riêng biệt
> db.countOrSizeDemo.distinct('StudentFirstName').length;
Kết quả: 4 (John, David, Carol, Sam)
Giải thích: distinct() trả về mảng giá trị duy nhất, .length đếm số phần tử. Cách này hiệu quả cho collection nhỏ/vừa. Với collection lớn, dùng aggregation $group + $addToSet + $size.