ใช้ operator $ne (Not Equal) สำหรับเงื่อนไขเดียว และ $nin (Not In) สำหรับหลายเงื่อนไข เพื่อดึงเอกสารที่ ไม่ตรงกับค่าที่ระบุ
รูปแบบคำสั่ง
Case 1: ยกเว้นค่าเดียว ($ne)
db.collection.find({ "fieldName": { $ne: "excludedValue" } }).pretty();
Case 2: ยกเว้นหลายค่า ($nin)
db.collection.find({ "fieldName": { $nin: ["value1", "value2", ...] } }).pretty();
ตัวอย่างเต็มรูปแบบ
1. สร้างข้อมูลตัวอย่าง
> db.findAllExceptFromOneOrtwoDemo.insertOne({"StudentName":"Larry","StudentSubjectName":"Java"});
> db.findAllExceptFromOneOrtwoDemo.insertOne({"StudentName":"Chris","StudentSubjectName":"C++"});
> db.findAllExceptFromOneOrtwoDemo.insertOne({"StudentName":"Robert","StudentSubjectName":"C"});
> db.findAllExceptFromOneOrtwoDemo.insertOne({"StudentName":"David","StudentSubjectName":"Python"});
2. แสดงข้อมูลทั้งหมด
{ "_id" : ..., "StudentName" : "Larry", "StudentSubjectName" : "Java" }
{ "_id" : ..., "StudentName" : "Chris", "StudentSubjectName" : "C++" }
{ "_id" : ..., "StudentName" : "Robert", "StudentSubjectName" : "C" }
{ "_id" : ..., "StudentName" : "David", "StudentSubjectName" : "Python" }
Case 1: ยกเว้น "C" (เงื่อนไขเดียว)
> db.findAllExceptFromOneOrtwoDemo.find({ StudentSubjectName: { $ne: "C" } }).pretty();
{ "_id" : ..., "StudentName" : "Larry", "StudentSubjectName" : "Java" }
{ "_id" : ..., "StudentName" : "Chris", "StudentSubjectName" : "C++" }
{ "_id" : ..., "StudentName" : "David", "StudentSubjectName" : "Python" }
Case 2: ยกเว้น "C++" และ "Python" (สองเงื่อนไข)
> db.findAllExceptFromOneOrtwoDemo.find({ StudentSubjectName: { $nin: ["C++", "Python"] } }).pretty();
{ "_id" : ..., "StudentName" : "Larry", "StudentSubjectName" : "Java" }
{ "_id" : ..., "StudentName" : "Robert", "StudentSubjectName" : "C" }
Operator เปรียบเทียบ
| Operator | ความหมาย | ใช้เมื่อ |
|---|---|---|
$ne | Not Equal | ยกเว้น 1 ค่า |
$nin | Not In Array | ยกเว้นหลายค่า |
$not | Logical NOT | Logic ซับซ้อน/Regex |
สรุป
$neสำหรับ exclude ค่าเดียว$ninสำหรับ exclude หลายค่า (array)- ทั้งคู่ทำงานได้กับทุกชนิดข้อมูล (string, number, boolean, date)
- สามารถรวมกับ operator อื่นได้ เช่น
{ $and: [ { field: { $ne: "x" } }, { other: 1 } ] }