How to delete partial data in MongoDB?

MongoDBDatabaseBig Data Analytics

Set the value to be deleted in a variable To delete particle data, use remove(). Let us create a collection with documents −

> 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")
}

Display all documents from a collection with the help of find() method −

> db.demo488.find();

This will produce the following output −

{ "_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" }

Following is the query to delete partial data in 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 })

Display all documents from a collection with the help of find() method −

> db.demo488.find();

This will produce the following output −

{ "_id" : ObjectId("5e8351e0b0f3fa88e22790b2"), "Name" : "Chris" }
{ "_id" : ObjectId("5e8351e8b0f3fa88e22790b3"), "Name" : "David" }
{ "_id" : ObjectId("5e8351ebb0f3fa88e22790b4"), "Name" : "Bob" }
{ "_id" : ObjectId("5e8351eeb0f3fa88e22790b5"), "Name" : "Mike" }
raja
Published on 11-May-2020 10:01:39
Advertisements