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

Làm cách nào để xóa một phần dữ liệu trong MongoDB?


Đặt giá trị bị xóa trong một biến Để xóa dữ liệu hạt, hãy sử dụng remove (). Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -

> db.demo488.insertOne({"Name":"Chris"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8351e0b0f3fa88e22790b2")
}
> db.demo488.insertOne({"Name":"David"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8351e8b0f3fa88e22790b3")
}
> db.demo488.insertOne({"Name":"Bob"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8351ebb0f3fa88e22790b4")
}
> db.demo488.insertOne({"Name":"Mike"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8351eeb0f3fa88e22790b5")
}
> db.demo488.insertOne({"Name":"Sam"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e835202b0f3fa88e22790b6")
}
> db.demo488.insertOne({"Name":"John"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e835207b0f3fa88e22790b7")
}
> db.demo488.insertOne({"Name":"Robert"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e83520cb0f3fa88e22790b8")
}

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 () -

> db.demo488.find();

Điều này sẽ tạo ra kết quả sau -

{ "_id" : ObjectId("5e8351e0b0f3fa88e22790b2"), "Name" : "Chris" }
{ "_id" : ObjectId("5e8351e8b0f3fa88e22790b3"), "Name" : "David" }
{ "_id" : ObjectId("5e8351ebb0f3fa88e22790b4"), "Name" : "Bob" }
{ "_id" : ObjectId("5e8351eeb0f3fa88e22790b5"), "Name" : "Mike" }
{ "_id" : ObjectId("5e835202b0f3fa88e22790b6"), "Name" : "Sam" }
{ "_id" : ObjectId("5e835207b0f3fa88e22790b7"), "Name" : "John" }
{ "_id" : ObjectId("5e83520cb0f3fa88e22790b8"), "Name" : "Robert" }

Sau đây là truy vấn để xóa một phần dữ liệu trong MongoDB -

> var deleteData = db.demo488.find({}, {_id : 1}).skip(4).toArray().map(function(d) { return
d._id; });
> db.demo488.remove({_id: {$in: deleteData}})
WriteResult({ "nRemoved" : 3 })

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 () -

> db.demo488.find();

Điều này sẽ tạo ra kết quả sau -

{ "_id" : ObjectId("5e8351e0b0f3fa88e22790b2"), "Name" : "Chris" }
{ "_id" : ObjectId("5e8351e8b0f3fa88e22790b3"), "Name" : "David" }
{ "_id" : ObjectId("5e8351ebb0f3fa88e22790b4"), "Name" : "Bob" }
{ "_id" : ObjectId("5e8351eeb0f3fa88e22790b5"), "Name" : "Mike" }