Computer >> Máy Tính >  >> Lập trình >> MongoDB

Xóa đối tượng khỏi mảng trong MongoDB?

Để xóa đối tượng khỏi một mảng trong MongoDB, bạn có thể sử dụng toán tử $ pull. Cú pháp như sau:

db.yourCollectionName.update( {'_id':ObjectId("5c6ea036a0c51185aefbd14f")},
{$pull:{"yourArrayName":{"yourArrayFieldName":yourValue}}},
false,true);

Để hiểu cú pháp trên, chúng ta hãy tạo một bộ sưu tập với tài liệu. Truy vấn để tạo một bộ sưu tập với tài liệu như sau:

> db.removeObject.insertOne({"CustomerName":"Maxwell","CustomerAge":23,
... "CustomerDetails":[
... {
... "CustomerId":100,
... "CustomerProduct":"Product-1"
... },
... {
... "CustomerId":150,
... "CustomerProduct":"Product-2"
... },
... {
... "CustomerId":200,
... "CustomerProduct":"Product-3"
... }
... ]
... });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ea036a0c51185aefbd14f")
}

Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find (). Truy vấn như sau:

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

Sau đây là kết quả:

{
   "_id" : ObjectId("5c6ea036a0c51185aefbd14f"),
   "CustomerName" : "Maxwell",
   "CustomerAge" : 23,
   "CustomerDetails" : [
      {
         "CustomerId" : 100,
         "CustomerProduct" : "Product-1"
      },
      {
         "CustomerId" : 150,
         "CustomerProduct" : "Product-2"
      },
      {
         "CustomerId" : 200,
         "CustomerProduct" : "Product-3"
      }
   ]
}

Đây là truy vấn để xóa đối tượng khỏi một mảng trong MongoDB:

> db.removeObject.update( {'_id':ObjectId("5c6ea036a0c51185aefbd14f")},
... {$pull:{"CustomerDetails":{"CustomerId":150}}},
... false,true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Ở trên, chúng tôi đã xóa đối tượng khỏi một mảng. Hãy để chúng tôi hiển thị tài liệu từ bộ sưu tập. Truy vấn như sau:

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

Sau đây là kết quả:

{
   "_id" : ObjectId("5c6ea036a0c51185aefbd14f"),
   "CustomerName" : "Maxwell",
   "CustomerAge" : 23,
   "CustomerDetails" : [
      {
         "CustomerId" : 100,
         "CustomerProduct" : "Product-1"
      },
      {
         "CustomerId" : 200,
         "CustomerProduct" : "Product-3"
      }
   ]
}