Operator $elemMatch ใน MongoDB ใช้สำหรับ Match เอกสารที่มี Element ใน Array ตรงตามเงื่อนไขหลายอย่างพร้อมกัน (ใน Element เดียวกัน) เนื้อหานี้สาธิตการค้นหาเอกสารที่ Array ClientDetails มี Element ที่ ClientProject เป็น "Online Banking System"
ตัวอย่างข้อมูลทดสอบ
> db.demo153.insertOne({
"ClientDetails":[
{"ClientName":"Chris","ClientProject":"Online Banking System"},
{"ClientName":"David","ClientProject":"Online School Management"}
]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e351957fdf09dd6d08539df") }
> db.demo153.insertOne({
"ClientDetails":[
{"ClientName":"Carol","ClientProject":"Online Book System"},
{"ClientName":"Mike","ClientProject":"Game Development"}
]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3519c9fdf09dd6d08539e0") }
แสดงข้อมูลทั้งหมด
> db.demo153.find();
{
"_id" : ObjectId("5e351957fdf09dd6d08539df"),
"ClientDetails" : [
{ "ClientName" : "Chris", "ClientProject" : "Online Banking System" },
{ "ClientName" : "David", "ClientProject" : "Online School Management" }
]
}
{
"_id" : ObjectId("5e3519c9fdf09dd6d08539e0"),
"ClientDetails" : [
{ "ClientName" : "Carol", "ClientProject" : "Online Book System" },
{ "ClientName" : "Mike", "ClientProject" : "Game Development" }
]
}
Query ใช้ $elemMatch
> db.demo153.find({
"ClientDetails": {
"$elemMatch": {
"ClientProject": { "$in": ["Online Banking System"] }
}
}
});
ผลลัพธ์
{
"_id" : ObjectId("5e351957fdf09dd6d08539df"),
"ClientDetails" : [
{ "ClientName" : "Chris", "ClientProject" : "Online Banking System" },
{ "ClientName" : "David", "ClientProject" : "Online School Management" }
]
}
คำอธิบายและข้อสังเกต
$elemMatchต้องการให้ Element เดียว Match ทุกเงื่อนไขใน Object- ตัวอย่างใช้
$inแม้จะมีค่าเดียว ก็ทำงานได้ (เหมือน Equals) - ผลลัพธ์คืน ทั้งเอกสาร (Whole Document) รวม Element อื่นใน Array ด้วย
- หากต้องการคืนเฉพาะ Element ที่ Match ใช้
$elemMatchใน Projection:db.demo153.find( { "ClientDetails.ClientProject": "Online Banking System" }, { ClientDetails: { $elemMatch: { ClientProject: "Online Banking System" } } } ) - ความต่าง: Dot Notation (
details.field) Match ได้จาก Element ต่างกันใน Array, $elemMatch ต้องเป็น Element เดียวกัน