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

MongoDB $in Operator ค้นหาหลายเอกสารด้วย Array ของค่า

Operator $in ใน MongoDB ใช้สำหรับ Match เอกสารที่ Field มีค่า อยู่ใน Array ที่ระบุ (Equivalent to SQL IN) เนื้อหานี้สาธิตการค้นหาเอกสารที่ ClientId เป็น 101, 103, หรือ 104

ตัวอย่างข้อมูลทดสอบ

> db.demo161.insertOne({"ClientId":101,"ClientName":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3577cafdf09dd6d0853a09") }

> db.demo161.insertOne({"ClientId":102,"ClientName":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3577d0fdf09dd6d0853a0a") }

> db.demo161.insertOne({"ClientId":103,"ClientName":"David","ClientAge":35});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3577dffdf09dd6d0853a0b") }

> db.demo161.insertOne({"ClientId":104,"ClientName":"Carol","ClientAge":31});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3577eefdf09dd6d0853a0c") }

แสดงข้อมูลทั้งหมด

> db.demo161.find();
{
  "_id" : ObjectId("5e3577cafdf09dd6d0853a09"),
  "ClientId" : 101, "ClientName" : "Chris"
}
{
  "_id" : ObjectId("5e3577d0fdf09dd6d0853a0a"),
  "ClientId" : 102, "ClientName" : "David"
}
{
  "_id" : ObjectId("5e3577dffdf09dd6d0853a0b"),
  "ClientId" : 103, "ClientName" : "David", "ClientAge" : 35
}
{
  "_id" : ObjectId("5e3577eefdf09dd6d0853a0c"),
  "ClientId" : 104, "ClientName" : "Carol", "ClientAge" : 31
}

Query ใช้ $in

> db.demo161.find({ClientId: {$in: [101, 103, 104]}});

ผลลัพธ์ (Match 3 เอกสาร)

{
  "_id" : ObjectId("5e3577cafdf09dd6d0853a09"),
  "ClientId" : 101, "ClientName" : "Chris"
}
{
  "_id" : ObjectId("5e3577dffdf09dd6d0853a0b"),
  "ClientId" : 103, "ClientName" : "David", "ClientAge" : 35
}
{
  "_id" : ObjectId("5e3577eefdf09dd6d0853a0c"),
  "ClientId" : 104, "ClientName" : "Carol", "ClientAge" : 31
}

คำอธิบายและข้อมูลเพิ่มเติม

  • $in: [value1, value2, ...] Match ถ้า Field Value อยู่ใน Array นั้น
  • ทำงานได้กับทุก Data Type (Number, String, ObjectId, Date, etc.)
  • Performance: ใช้ Index ได้ (Multi-key Index) - เร็วกว่า $or สำหรับ Field เดียว
  • ตรงข้าม: $nin (Not In) - Match ถ้าไม่อยู่ใน Array
  • ตัวอย่าง $nin: {ClientId: {$nin: [101, 103, 104]}} → ได้ ClientId 102
  • Array ใน Field: หาก Field เป็น Array (เช่น tags: ["a","b"]), {tags: {$in: ["a"]}} Match ถ้า Array มี "a"