Để kiểm tra sự tồn tại của tài liệu và trả về boolean, dùng find() kết hợp count() so sánh với 0.
Ví dụ: Collection documentExistsOrNotDemo:
> db.documentExistsOrNotDemo.insertOne({"UserId":101,"UserName":"John"});
> db.documentExistsOrNotDemo.insertOne({"UserId":102,"UserName":"Chris"});
> db.documentExistsOrNotDemo.insertOne({"UserId":102,"UserName":"Robert"});
Trường hợp 1: Tài liệu tồn tại (UserId = 101):
> db.documentExistsOrNotDemo.find({ "UserId": 101 }).count() > 0;
True
Trường hợp 2: Tài liệu KHÔNG tồn tại (UserId = 110):
> db.documentExistsOrNotDemo.find({ "UserId": 110 }).count() > 0;
False
Lưu ý (MongoDB 4.0+): count() trên cursor đã deprecated. Nên dùng:
countDocuments({ query })- chính xác, hỗ trợ filter.estimatedDocumentCount()- nhanh, ước lượng toàn collection.
Cách hiện đại:
db.documentExistsOrNotDemo.countDocuments({ "UserId": 101 }) > 0; // true
db.documentExistsOrNotDemo.countDocuments({ "UserId": 110 }) > 0; // false