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

MongoDB Query เปรียบเทียบ Field ใน Document เดียวกัน

เปรียบเทียบ Field ใน Document เดียวกันด้วย $where

ใช้ $where พร้อม JavaScript เพื่อเปรียบเทียบค่าระหว่าง Field ใน Document เดียวกัน

สร้างข้อมูลตัวอย่าง

> db.queryInSameDocumentsDemo.insertOne({"StudentDetails":{"StudentName":"John"},"NewStudentDetails":{"StudentName":"Carol"}});
{ "acknowledged" : true, "insertedId" : ObjectId("5c90096ed3c9d04998abf017") }
> db.queryInSameDocumentsDemo.insertOne({"StudentDetails":{"StudentName":"Bob"},"NewStudentDetails":{"StudentName":"Bob"}});
{ "acknowledged" : true, "insertedId" : ObjectId("5c900a435705caea966c5573") }

กรณีที่ 1: Field เท่ากัน (==)

> db.queryInSameDocumentsDemo.find( { $where: "this.StudentDetails.StudentName == this.NewStudentDetails.StudentName" } ).pretty();
{ "_id" : ObjectId("5c900a435705caea966c5573"), "StudentDetails" : { "StudentName" : "Bob" }, "NewStudentDetails" : { "StudentName" : "Bob" } }

กรณีที่ 2: Field ไม่เท่ากัน (!=)

> db.queryInSameDocumentsDemo.find( { $where: "this.StudentDetails.StudentName != this.NewStudentDetails.StudentName" } ).pretty();
{ "_id" : ObjectId("5c90096ed3c9d04998abf017"), "StudentDetails" : { "StudentName" : "John" }, "NewStudentDetails" : { "StudentName" : "Carol" } }

หมายเหตุ: $where ใช้ JavaScript Engine ทำให้ช้ากว่า Operator ปกติ ควรใช้เฉพาะกรณีที่จำเป็น