Kiểm tra tồn tại nhiều trường cùng lúc với $exists + $and
Sử dụng $exists: true kết hợp $and để tìm document có đầy đủ các trường yêu cầu.
1. Dữ liệu: Document có trường khác nhau
> db.demo475.insertOne({ StudentFirstName: "Chris", StudentAge: 23 });
> db.demo475.insertOne({ StudentFirstName: "Bob", StudentAge: 21, StudentCountryName: "US" });
> db.demo475.insertOne({ StudentFirstName: "David", StudentAge: 22 });
2. Tìm document có CẢ 3 trường: FirstName, Age, CountryName
> db.demo475.find({
$and: [
{ StudentFirstName: { $exists: true } },
{ StudentAge: { $exists: true } },
{ StudentCountryName: { $exists: true } }
]
});
3. Kết quả
{
"_id": ObjectId("5e80c127b0f3fa88e2279089"),
"StudentFirstName": "Bob",
"StudentAge": 21,
"StudentCountryName": "US"
}
Cách viết gọn hơn (implicit AND)
// Tương đương (find() ngầm hiểu AND giữa các field)
db.demo475.find({
StudentFirstName: { $exists: true },
StudentAge: { $exists: true },
StudentCountryName: { $exists: true }
});
$exists: true vs $exists: false
| Toán tử | Khớp khi | Ví dụ |
|---|---|---|
| { field: { $exists: true } } | Trường tồn tại (kể cả giá trị null) | { a: null } → KHỚP |
| { field: { $exists: false } } | Trường KHÔNG tồn tại | { b: 1 } → KHỚP (với field a) |
Kết hợp với giá trị cụ thể
// Tồn tại VÀ không null
db.find({ field: { $exists: true, $ne: null } });
// Tồn tại VÀ là string
db.find({ field: { $exists: true, $type: "string" } });
// Không tồn tại HOẶC null
db.find({ $or: [{ field: { $exists: false } }, { field: null }] });
Ứng dụng: Data Quality Check
// Tìm document thiếu trường bắt buộc
db.users.find({
$or: [
{ email: { $exists: false } },
{ phone: { $exists: false } },
{ address: { $exists: false } }
]
});
// Hoặc dùng $nor (logic NOR)
db.users.find({
$nor: [
{ email: { $exists: true } },
{ phone: { $exists: true } },
{ address: { $exists: true } }
]
});
Index cho $exists
// Partial index: chỉ index document CÓ trường này
db.demo475.createIndex(
{ StudentCountryName: 1 },
{ partialFilterExpression: { StudentCountryName: { $exists: true } } }
);