MongoDB không có toán tử NOT LIKE như SQL. Sử dụng $not kết hợp $regex để đạt hiệu quả tương tự.
Ví dụ minh họa
Tạo collection notLikeOperatorDemo:
> db.notLikeOperatorDemo.insertOne({"TenSinhVien": "John Doe"});
> db.notLikeOperatorDemo.insertOne({"TenSinhVien": "John Smith"});
> db.notLikeOperatorDemo.insertOne({"TenSinhVien": "John Taylor"});
> db.notLikeOperatorDemo.insertOne({"TenSinhVien": "Carol Taylor"});
> db.notLikeOperatorDemo.insertOne({"TenSinhVien": "David Miller"});
Tìm KHÔNG phải "John Taylor"
> db.notLikeOperatorDemo.find({TenSinhVien: {$not: /^John Taylor.*/}});
Kết quả (4 document khác):
{ "TenSinhVien": "John Doe" }
{ "TenSinhVien": "John Smith" }
{ "TenSinhVien": "Carol Taylor" }
{ "TenSinhVien": "David Miller" }
Cách viết khác
> db.notLikeOperatorDemo.find({TenSinhVien: {$not: /John Taylor/}});
Tương tự nhưng khớp chuỗi con bất kỳ vị trí.
So sánh SQL vs MongoDB
| SQL | MongoDB |
|---|---|
| NOT LIKE 'John%' | {$not: /^John/} |
| NOT LIKE '%Taylor' | {$not: /Taylor$/} |
| NOT LIKE '%John%' | {$not: /John/} |
Lưu ý: $not với regex không dùng index. Cân nhắc logic phủ định ở application layer cho performance tốt hơn.