Để lấy tài liệu ngoại trừ một số tài liệu cụ thể, sử dụng $nor kết hợp $and.
Tạo collection:
> db.demo1.insertOne({"StudentName":"Chris","StudentMarks":38});
{ "acknowledged" : true, "insertedId" : ObjectId("5e08a4f025ddae1f53b62216") }
> db.demo1.insertOne({"StudentName":"David","StudentMarks":78});
{ "acknowledged" : true, "insertedId" : ObjectId("5e08a4f725ddae1f53b62217") }
> db.demo1.insertOne({"StudentName":"Mike","StudentMarks":96});
{ "acknowledged" : true, "insertedId" : ObjectId("5e08a4fd25ddae1f53b62218") }
Hiển thị dữ liệu:
> db.demo1.find().pretty();
{ "_id" : ObjectId("5e08a4f025ddae1f53b62216"), "StudentName" : "Chris", "StudentMarks" : 38 }
{ "_id" : ObjectId("5e08a4f725ddae1f53b62217"), "StudentName" : "David", "StudentMarks" : 78 }
{ "_id" : ObjectId("5e08a4fd25ddae1f53b62218"), "StudentName" : "Mike", "StudentMarks" : 96 }
Truy vấn ngược: lấy tất cả KHÔNG phải (StudentName="David" VÀ StudentMarks=78):
> db.demo1.find({$nor:[{$and:[{'StudentName':'David'},{'StudentMarks':78}]}]});
Kết quả loại bỏ David/78, giữ lại Chris/38 và Mike/96:
{ "_id" : ObjectId("5e08a4f025ddae1f53b62216"), "StudentName" : "Chris", "StudentMarks" : 38 }
{ "_id" : ObjectId("5e08a4fd25ddae1f53b62218"), "StudentName" : "Mike", "StudentMarks" : 96 }