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

MongoDB Query: ใช้ OR Operator ใน find()

Operator $or ใน MongoDB ใช้สำหรับ query แบบ "หรือ" (Logical OR) - คืนค่าเอกสารที่ตรงกับ อย่างน้อยหนึ่งเงื่อนไข จากรายการที่กำหนด

สร้างคอลเลกชันและข้อมูลตัวอย่าง

> db.demo78.insertOne({"Name1":"Chris","Name2":"Mike"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2bd99c71bf0181ecc4228f") }
> db.demo78.insertOne({"Name1":"Bob","Name2":"Carol"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2bd9ac71bf0181ecc42290") }
> db.demo78.insertOne({"Name1":"David","Name2":"Sam"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2bd9b671bf0181ecc42291") }
> db.demo78.insertOne({"Name1":"Jace","Name2":"John"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2bd9bf71bf0181ecc42292") }

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

> db.demo78.find();

ผลลัพธ์:

{ "_id" : ObjectId("5e2bd99c71bf0181ecc4228f"), "Name1" : "Chris", "Name2" : "Mike" }
{ "_id" : ObjectId("5e2bd9ac71bf0181ecc42290"), "Name1" : "Bob", "Name2" : "Carol" }
{ "_id" : ObjectId("5e2bd9b671bf0181ecc42291"), "Name1" : "David", "Name2" : "Sam" }
{ "_id" : ObjectId("5e2bd9bf71bf0181ecc42292"), "Name1" : "Jace", "Name2" : "John" }

Query ใช้ $or ค้นหา Name1="Bob" หรือ Name2="John"

> db.demo78.find({$or: [{"Name1": "Bob"}, {Name2: "John"}] });

ผลลัพธ์

{ "_id" : ObjectId("5e2bd9ac71bf0181ecc42290"), "Name1" : "Bob", "Name2" : "Carol" }
{ "_id" : ObjectId("5e2bd9bf71bf0181ecc42292"), "Name1" : "Jace", "Name2" : "John" }

คำอธิบาย:

  • เอกสารที่ 1: Name1="Bob" ตรงเงื่อนไขแรก
  • เอกสารที่ 4: Name2="John" ตรงเงื่อนไขที่สอง
  • เอกสารที่ 2 และ 3: ไม่ตรงเงื่อนไขใดเลย

รูปแบบทั่วไปของ $or

{ $or: [ { :  }, { :  }, ... ] }

การรวม $or กับ $and

สามารถรวมได้ เช่น ค้นหา (Name1=Bob หรือ Name2=John) และ Age > 20:

db.demo78.find({
  $and: [
    { $or: [ {"Name1": "Bob"}, {"Name2": "John"} ] },
    { "Age": { $gt: 20 } }
  ]
})

ประสิทธิภาพ: $or อาจช้ากว่า query ธรรมดา หากใช้บ่อยควรสร้าง index บน field ที่ query บ่อย