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

การเปรียบเทียบหลายคุณสมบัติ (Multiple Properties) ใน MongoDB

ใช้ตัวดำเนินการ $where เพื่อเปรียบเทียบค่าระหว่างหลายฟิลด์หรือหลายตำแหน่งในอาร์เรย์ เริ่มต้นด้วยการสร้างคอลเลกชันตัวอย่าง:

> db.comparingMultiplePropertiesDemo.insertOne({"Values":[10,70,60]});
{ "acknowledged" : true, "insertedId" : ObjectId("5cf228fcb64a577be5a2bc0a") }

แสดงเอกสาร:

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

กรณีที่ 1: เงื่อนไขเป็นจริง (Values[1] > Values[2] คือ 70 > 60)

> db.comparingMultiplePropertiesDemo.find({ $where : "this.Values[1] > this.Values[2]" });

กรณีที่ 2: เงื่อนไขเป็นเท็จ (Values[1] < Values[2] คือ 70 < 60)

> db.comparingMultiplePropertiesDemo.find({ $where : "this.Values[1] < this.Values[2]" });

ไม่มีข้อมูลแสดง เพราะเงื่อนไขเป็นเท็จ

หมายเหตุ: ในฟังก์ชัน $where ใช้ this เพื่ออ้างถึงเอกสารปัจจุบัน และเข้าถึงอาร์เรย์ด้วยดัชนี [0], [1], [2]... ตัวดำเนินการ $where ใช้ JavaScript engine ทำให้ช้ากว่าตัวดำเนินการมาตรฐาน ควรใช้ רקเมื่อจำเป็น