Operator $where ใน MongoDB อนุญาตให้ใช้ JavaScript expression ในการ query เหมาะสำหรับเปรียบเทียบ field กับ field (cross-field comparison) ที่ operator ธรรมดาทำไม่ได้
สร้างคอลเลกชันและข้อมูลตัวอย่าง
> db.demo223.insertOne({"Scores":[56,78]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3ee4ca03d395bdc2134730") }
> db.demo223.insertOne({"Scores":[88,45]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3ee4d103d395bdc2134731") }
> db.demo223.insertOne({"Scores":[98,79]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3ee4d803d395bdc2134732") }
แสดงข้อมูลทั้งหมด
> db.demo223.find();
ผลลัพธ์: 3 เอกสาร แต่ละอันมี Scores array 2 elements
Query เปรียบเทียบ Scores[0] > Scores[1] ด้วย $where
> db.demo223.find({ $where : "this.Scores[0] > this.Scores[1]" });
ผลลัพธ์
{ "_id" : ObjectId("5e3ee4d103d395bdc2134731"), "Scores" : [ 88, 45 ] }
{ "_id" : ObjectId("5e3ee4d803d395bdc2134732"), "Scores" : [ 98, 79 ] }
เอกสารที่ 1: 56 > 78 = false (ไม่ผ่าน)
เอกสารที่ 2: 88 > 45 = true (ผ่าน)
เอกสารที่ 3: 98 > 79 = true (ผ่าน)
คำอธิบาย $where:
this= current document- เขียน JavaScript expression คืนค่า true/false
- เข้าถึง field ได้แบบ
this.fieldNameหรือthis["field-name"] - เข้าถึง array element:
this.Scores[0]
⚠️ ข้อจำกัดและคำเตือนสำคัญ
| ปัญหา | รายละเอียด |
|---|---|
| Performance | Slow - ต้อง evaluate JavaScript ทุก document ไม่ใช้ index |
| Security | Risk injection - ไม่ควรใช้ user input ตรงๆ |
| Concurrency | Single-threaded JS engine บล็อก operations อื่น |
| Sharding | ไม่รองรับ sharded collections |