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

วิธีลบสมาชิกอาร์เรย์ตามดัชนีใน MongoDB

ในการลบสมาชิกอาร์เรย์ตามดัชนีใน MongoDB คุณสามารถใช้โอเปอเรเตอร์ $unset และ $pull ร่วมกัน กระบวนการมี 2 ขั้นตอนหลัก ดังนี้

ไวยากรณ์

db.yourCollectionName.update({},{$unset:{"yourArrayListName.yourPosition":yourPositionValue}});
db.yourCollectionName.update({},{$pull:{"yourArrayListName":null}});

ตัวอย่างการใช้งาน

สร้างคอลเลกชันพร้อมเอกสารตัวอย่าง:

> db.removeArrayElements.insertOne({"StudentName":"Larry","StudentAge":23,"TechnicalSubject":["C","C++","Java","MongoDB"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c6ea4879c4643706aef56d2") }

แสดงข้อมูลทั้งหมดด้วย find():

> db.removeArrayElements.find().pretty();
{
  "_id" : ObjectId("5c6ea4879c4643706aef56d2"),
  "StudentName" : "Larry",
  "StudentAge" : 23,
  "TechnicalSubject" : [
    "C",
    "C++",
    "Java",
    "MongoDB"
  ]
}

ลบสมาชิกที่ดัชนี 3 (คือ "MongoDB"):

> db.removeArrayElements.update({},{$unset:{"TechnicalSubject.3":1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.removeArrayElements.update({},{$pull:{"TechnicalSubject":null}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

ตรวจสอบผลลัพธ์:

> db.removeArrayElements.find().pretty();
{
  "_id" : ObjectId("5c6ea4879c4643706aef56d2"),
  "StudentName" : "Larry",
  "StudentAge" : 23,
  "TechnicalSubject" : [
    "C",
    "C++",
    "Java"
  ]
}

จากผลลัพธ์ จะเห็นว่าสมาชิกที่ดัชนี 3 (ตำแหน่งที่ 4) ถูกลบออกแล้ว