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

วิธีใช้เงื่อนไขเฉพาะเมื่อฟิลด์มีอยู่ใน MongoDB (Conditional Query)

ใช้ตัวดำเนินการ $or เพื่อใช้เงื่อนไขก็ต่อเมื่อฟิลด์มีอยู่จริง

ตัวอย่างการใช้งาน

สร้างคอลเลกชันพร้อมข้อมูล (เอกสารบางรายการไม่มีฟิลด์ StudentAge):

> db.applyConditionDemo.insertOne({"StudentName":"Larry","StudentAge":21,"StudentMarks":45});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb80b78623186894665ae36") }
> db.applyConditionDemo.insertOne({"StudentName":"Sam","StudentAge":23,"StudentMarks":55});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb80b87623186894665ae37") }
> db.applyConditionDemo.insertOne({"StudentName":"David","StudentAge":21,"StudentMarks":65});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb80b95623186894665ae38") }
> db.applyConditionDemo.insertOne({"StudentName":"Carol","StudentAge":24,"StudentMarks":78});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb80ba3623186894665ae39") }
> db.applyConditionDemo.insertOne({"StudentName":"Chris","StudentAge":21,"StudentMarks":88});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb80bae623186894665ae3a") }
> db.applyConditionDemo.insertOne({"StudentName":"Robert","StudentMarks":98});  // ไม่มี StudentAge
{ "acknowledged" : true, "insertedId" : ObjectId("5cb80c3d623186894665ae3b") }

แสดงเอกสารทั้งหมด:

> db.applyConditionDemo.find().pretty();

ผลลัพธ์ (Robert ไม่มี StudentAge):

{ "_id" : ObjectId("5cb80b78623186894665ae36"), "StudentName" : "Larry", "StudentAge" : 21, "StudentMarks" : 45 }
{ "_id" : ObjectId("5cb80b87623186894665ae37"), "StudentName" : "Sam", "StudentAge" : 23, "StudentMarks" : 55 }
{ "_id" : ObjectId("5cb80b95623186894665ae38"), "StudentName" : "David", "StudentAge" : 21, "StudentMarks" : 65 }
{ "_id" : ObjectId("5cb80ba3623186894665ae39"), "StudentName" : "Carol", "StudentAge" : 24, "StudentMarks" : 78 }
{ "_id" : ObjectId("5cb80bae623186894665ae3a"), "StudentName" : "Chris", "StudentAge" : 21, "StudentMarks" : 88 }
{ "_id" : ObjectId("5cb80c3d623186894665ae3b"), "StudentName" : "Robert", "StudentMarks" : 98 }

คิวรี่: เงื่อนไข StudentAge = 21 หรือ ฟิลด์ StudentAge ไม่มีอยู่

> db.applyConditionDemo.find({ $or: [ { StudentAge: { $exists:false } }, { StudentAge:21 } ]}).pretty();

ผลลัพธ์ (รวม Robert ที่ไม่มี StudentAge):

หลักการ: $or ทำงานแบบ "หรือ" - ตรงเงื่อนไขข้อไหนข้อนึงก็คืนค่า ใช้ร่วมกับ $exists: false เพื่อเช็คว่าฟิลด์ไม่มีอยู่จริง