ใน MongoDB สามารถใช้ operator $indexOfArray เพื่อค้นหาตำแหน่ง (index) ของค่าเฉพาะภายใน array field ได้ ตัวอย่างนี้สาธิตการใช้งานกับรุ่นเก่าของ MongoDB
สร้างคอลเลกชันและข้อมูลตัวอย่าง
> db.demo65.insertOne({"ListOfValues":[10,20,30]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e28990ecfb11e5c34d89938") }
> db.demo65.insertOne({"ListOfValues":[50,60,70,100]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e28991ecfb11e5c34d89939") }
> db.demo65.insertOne({"ListOfValues":[30,40,89,91,98]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e28992bcfb11e5c34d8993a") }
แสดงข้อมูลทั้งหมด
> db.demo65.find();
ผลลัพธ์:
{ "_id" : ObjectId("5e28990ecfb11e5c34d89938"), "ListOfValues" : [ 10, 20, 30 ] }
{ "_id" : ObjectId("5e28991ecfb11e5c34d89939"), "ListOfValues" : [ 50, 60, 70, 100 ] }
{ "_id" : ObjectId("5e28992bcfb11e5c34d8993a"), "ListOfValues" : [ 30, 40, 89, 91, 98 ] }
Query หา Index ของค่า 30 ใน Array
> db.demo65.aggregate([
... {
... $project: {
... IndexOfAnArrayElement: { $indexOfArray: [ "$ListOfValues", 30] }
... }
... }
... ]);
ผลลัพธ์
{ "_id" : ObjectId("5e28990ecfb11e5c34d89938"), "IndexOfAnArrayElement" : 2 }
{ "_id" : ObjectId("5e28991ecfb11e5c34d89939"), "IndexOfAnArrayElement" : -1 }
{ "_id" : ObjectId("5e28992bcfb11e5c34d8993a"), "IndexOfAnArrayElement" : 0 }
คำอธิบายผลลัพธ์:
- เอกสารที่ 1: ค่า 30 อยู่ที่ index 2 (นับจาก 0: 10, 20, 30)
- เอกสารที่ 2: ไม่พบค่า 30 คืนค่า -1
- เอกสารที่ 3: ค่า 30 อยู่ที่ index 0 (เป็นตัวแรกของ array)
หมายเหตุ: $indexOfArray จะคืนค่า index แรกที่พบเท่านั้น หากต้องการหาทุกตำแหน่งต้องใช้วิธีอื่น เช่น $filter หรือ $map