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

คิวรี่ MongoDB สำหรับลบองค์ประกอบอาร์เรย์ออกจากเอกสาร

ใช้ตัวดำเนินการ $pull เพื่อลบองค์ประกอบอาร์เรย์ออกจากเอกสาร MongoDB ไวยากรณ์ดังนี้:

db.yourCollectionName.update(
  { },
  { $pull: { yourFieldName: yourValue }},
  {multi:true}
);

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

>db.removeArrayElementsDemo.insertOne({"AllPlayerName":["John","Sam","Carol","David"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd90d011a844af18acdffc1") }
>db.removeArrayElementsDemo.insertOne({"AllPlayerName":["Chris","Robert","John","Mike"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd90d2e1a844af18acdffc2") }

แสดงเอกสารทั้งหมด:

> db.removeArrayElementsDemo.find().pretty();

ผลลัพธ์:

{ "_id" : ObjectId("5cd90d011a844af18acdffc1"), "AllPlayerName" : [ "John", "Sam", "Carol", "David" ] }
{ "_id" : ObjectId("5cd90d2e1a844af18acdffc2"), "AllPlayerName" : [ "Chris", "Robert", "John", "Mike" ] }

คิวรี่ลบค่า "John" ออกจากอาร์เรย์ AllPlayerName ในทุกเอกสาร:

> db.removeArrayElementsDemo.update(
  { },
  { $pull: { AllPlayerName: "John" }},
  {multi:true}
);
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

ตรวจสอบเอกสารอีกครั้ง:

> db.removeArrayElementsDemo.find().pretty();

ผลลัพธ์หลังลบ "John" แล้ว:

{ "_id" : ObjectId("5cd90d011a844af18acdffc1"), "AllPlayerName" : [ "Sam", "Carol", "David" ] }
{ "_id" : ObjectId("5cd90d2e1a844af18acdffc2"), "AllPlayerName" : [ "Chris", "Robert", "Mike" ] }