ลบ Array Element ตาม Index แบบ 2 ขั้นตอน
MongoDB ไม่มีคำสั่งลบ Array Element ตาม Index โดยตรง ต้องทำ 2 ขั้นตอน:
ขั้นตอนที่ 1: ตั้งค่า Element ที่ Index นั้นเป็น null
db.yourCollectionName.update({}, {$unset : {"yourArrayFieldName.yourIndexValue" : 1 }});
ขั้นตอนที่ 2: ลบค่า null ออกจาก Array ด้วย $pull
db.yourCollectionName.update({}, {$pull : {"yourArrayFieldName" : null}});
ตัวอย่างการลบ Element Index 2 (ค่า "Java")
> db.removeArrayElementByItsIndexDemo.insertOne({"InstructorName":"David", "InstructorAge":28,"InstructorSubject":["MongoDB","MySQL","Java","SQL Server","PL/SQL"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8abbfc6cea1f28b7aa0803") }
ขั้นตอนที่ 1: Unset Index 2
> db.removeArrayElementByItsIndexDemo.update({}, {$unset : {"InstructorSubject.2" : 1 }});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
ขั้นตอนที่ 2: Pull null ออก
> db.removeArrayElementByItsIndexDemo.update({}, {$pull : {"InstructorSubject" : null}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
ตรวจสอบผลลัพธ์
> db.removeArrayElementByItsIndexDemo.find().pretty();
{ "_id" : ObjectId("5c8abbfc6cea1f28b7aa0803"), "InstructorName" : "David", "InstructorAge" : 28, "InstructorSubject" : [ "MongoDB", "MySQL", "SQL Server", "PL/SQL" ] }
Element "Java" ที่ Index 2 ถูกลบออกแล้ว