ค้นหาค่าในอาร์เรย์และใช้ $or
MongoDB ค้นหาในอาร์เรย์ได้โดยตรง รองรับทั้ง exact match และ $or
ตัวอย่างข้อมูล
สร้างคอลเลกชัน andOrDemo ฟิลด์ StudentScore เป็นอาร์เรย์ตัวเลข:
> db.andOrDemo.insertOne({"StudentName":"Larry","StudentScore":[33,40,50,60,70]});
> db.andOrDemo.insertOne({"StudentName":"Larry","StudentScore":[87,67,79,98,90]});
ค้นหาที่มีค่า 70 ในอาร์เรย์
> db.andOrDemo.find({"StudentScore": 70}).pretty();
ผลลัพธ์: คืนเอกสารแรกที่มี 70 ในอาร์เรย์
ใช้ $or ค้นหาหลายค่า (OR condition)
> db.andOrDemo.find({$or: [{"StudentScore": 60}, {"StudentScore": 90}]}).pretty();
ผลลัพธ์: คืนทั้ง 2 เอกสาร (อันแรกมี 60, อันที่สองมี 90)
{ "_id" : ObjectId("..."), "StudentName" : "Larry", "StudentScore" : [33,40,50,60,70] }
{ "_id" : ObjectId("..."), "StudentName" : "Larry", "StudentScore" : [87,67,79,98,90] }
สำหรับ AND condition ในอาร์เรย์ ใช้ $all เช่น {StudentScore: {$all: [60, 70]}}