Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

วิธีค้นหาเอกสารใน MongoDB ยกเว้นเงื่อนไขที่กำหนด ($ne, $nin)

ใช้ 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ความหมายใช้เมื่อ
$neNot Equalยกเว้น 1 ค่า
$ninNot In Arrayยกเว้นหลายค่า
$notLogical NOTLogic ซับซ้อน/Regex

สรุป

  • $ne สำหรับ exclude ค่าเดียว
  • $nin สำหรับ exclude หลายค่า (array)
  • ทั้งคู่ทำงานได้กับทุกชนิดข้อมูล (string, number, boolean, date)
  • สามารถรวมกับ operator อื่นได้ เช่น { $and: [ { field: { $ne: "x" } }, { other: 1 } ] }