ใช้ $elemMatch ร่วมกับ $gt และ $lt เพื่อค้นหาเอกสารที่อาร์เรย์มีสมาชิกตรงตามเงื่อนไขหลายอย่างพร้อมกัน
ไวยากรณ์
db.yourCollectionName.find({yourFieldName:{$elemMatch:{$gt:yourNegativeValue,$lt:yourPositiveValue}}}).pretty();
ตัวอย่างการใช้งาน
สร้างคอลเลกชัน findValueInArrayWithMultipleCriteriaDemo:
> db.findValueInArrayWithMultipleCriteriaDemo.insertOne({"StudentName":"Larry","StudentMarks":[-150,150]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c77daf6fc4e719b197a12f5") }
> db.findValueInArrayWithMultipleCriteriaDemo.insertOne({"StudentName":"Mike","StudentMarks":[19]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c77db09fc4e719b197a12f6") }
แสดงข้อมูล:
> db.findValueInArrayWithMultipleCriteriaDemo.find().pretty();
{"_id" : ObjectId("5c77daf6fc4e719b197a12f5"), "StudentName" : "Larry", "StudentMarks" : [ -150, 150 ] }
{"_id" : ObjectId("5c77db09fc4e719b197a12f6"), "StudentName" : "Mike", "StudentMarks" : [ 19 ] }
ค้นหาเอกสารที่มีคะแนนในอาร์เรย์อยู่ระหว่าง -20 ถึง 20:
> db.findValueInArrayWithMultipleCriteriaDemo.find({StudentMarks:{$elemMatch:{$gt:-20,$lt:20}}}).pretty();
{"_id" : ObjectId("5c77db09fc4e719b197a12f6"), "StudentName" : "Mike", "StudentMarks" : [ 19 ] }
เอกสารของ Larry ถูกตัดออกเพราะไม่มีคะแนนในช่วงที่กำหนด