Remove document whose value is matched with $eq from a MongoDB collection?

MongoDBDatabaseBig Data Analytics

Remove document using remove(), whose value is matched with $eq from a MongoDB collection. The $eq operator matches documents where the value of a field equals the specified value.

Let us create a collection with documents −

> db.demo626.insertOne({id:1,"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9ac6376c954c74be91e6ae")
}
> db.demo626.insertOne({id:2,"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9ac63e6c954c74be91e6af")
}
> db.demo626.insertOne({id:3,"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9ac6436c954c74be91e6b0")
}
> db.demo626.insertOne({id:4,"Name":"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9ac6486c954c74be91e6b1")
}

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

> db.demo626.find();

This will produce the following output −

{ "_id" : ObjectId("5e9ac6376c954c74be91e6ae"), "id" : 1, "Name" : "Chris" }
{ "_id" : ObjectId("5e9ac63e6c954c74be91e6af"), "id" : 2, "Name" : "David" }
{ "_id" : ObjectId("5e9ac6436c954c74be91e6b0"), "id" : 3, "Name" : "Bob" }
{ "_id" : ObjectId("5e9ac6486c954c74be91e6b1"), "id" : 4, "Name" : "Mike" }

Following is the query to remove document from collection −

> db.demo626.remove({Name:{$eq:"Bob"}});
WriteResult({ "nRemoved" : 1 })

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

> db.demo626.find();

This will produce the following output −

{ "_id" : ObjectId("5e9ac6376c954c74be91e6ae"), "id" : 1, "Name" : "Chris" }
{ "_id" : ObjectId("5e9ac63e6c954c74be91e6af"), "id" : 2, "Name" : "David" }
{ "_id" : ObjectId("5e9ac6486c954c74be91e6b1"), "id" : 4, "Name" : "Mike" }
raja
Published on 12-May-2020 10:38:11
Advertisements