บทความนี้สาธิตวิคว์รี Array โดยใช้ Dot Notation ร่วมกับ Index เพื่อตรวจสอบค่าที่ตำแหน่งเฉพาะ (Index n) ว่าเป็น true หรือไม่
สร้างข้อมูลตัวอย่าง
> db.containsTrueValueDemo.insertOne({"IsMarried":[true,false,true,true,true,true,false,true,false,false,true]});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd5039c2cba06f46efe9ef5") }
แสดงข้อมูล
> db.containsTrueValueDemo.find().pretty();
{
"_id" : ObjectId("5cd5039c2cba06f46efe9ef5"),
"IsMarried" : [ true, false, true, true, true, true, false, true, false, false, true ]
}
ค้นหาเอกสารที่ Index 2 มีค่า true
Index 2 คือรายการที่ 3 (นับจาก 0)
> db.containsTrueValueDemo.find({'IsMarried.2' : true});
{
"_id" : ObjectId("5cd5039c2cba06f46efe9ef5"),
"IsMarried" : [ true, false, true, true, true, true, false, true, false, false, true ]
}
ค้นหาเอกสารที่ Index 0 และ Index 2 เป็น true พร้อมกัน (ใช้ $and)
> db.containsTrueValueDemo.find({
$and : [
{'IsMarried.0' : true},
{'IsMarried.2' : true}
]
});
{
"_id" : ObjectId("5cd5039c2cba06f46efe9ef5"),
"IsMarried" : [ true, false, true, true, true, true, false, true, false, false, true ]
}
สรุปเทคนิค
- ใช้
ArrayName.Index(Dot Notation) เพื่อเข้าถึงค่าตาม Index โดยตรง - Index เริ่มจาก 0 (Zero-based indexing)
- รวมเงื่อนไขหลาย Index ได้ด้วย
$and - ใช้ได้กับ Array ของ Primitive values (boolean, number, string) และ Array of Objects
ตัวอย่างเพิ่มเติม: Array of Objects
// หาเอกสารที่ Object ตัวที่ 2 (index 1) มี status = "active"
db.collection.find({ "items.1.status": "active" })