Remove and update the existing record in MongoDB?

MongoDBDatabaseBig Data Analytics

You can use only $pull operator that removes and updates the existing record in MongoDB. Let us first create a collection with documents −

> db.removeDemo.insertOne(
...    {
...       "UserName" : "Larry",
...       "UserDetails" : [
...          {
...             "_id" : 101,
...             "UserEmailId" : "976Larry@gmail.com",
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc7f9f88f9e6ff3eb0ce446")
}
> db.removeDemo.insertOne(
...    {
...       "UserName" : "Mike",
...       "UserDetails" : [
...          {
...             "_id" : 102,
...             "UserEmailId" : "Mike121@gmail.com",
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc7f9f98f9e6ff3eb0ce447")
}

Following is the query to display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5cc7f9f88f9e6ff3eb0ce446"),
   "UserName" : "Larry",
   "UserDetails" : [
      {
         "_id" : 101,
         "UserEmailId" : "976Larry@gmail.com"
      }
   ]
}
{
   "_id" : ObjectId("5cc7f9f98f9e6ff3eb0ce447"),
   "UserName" : "Mike",
   "UserDetails" : [
      {
         "_id" : 102,
         "UserEmailId" : "Mike121@gmail.com"
      }
   ]
}

Let us now implement the $pull query to remove and update the existing record −

> db.removeDemo.update(
...    {"_id": ObjectId("5cc7f9f98f9e6ff3eb0ce447")},
...    { "$pull": { "UserDetails": {"_id": 102}}}
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us display the documents from the collection in order to check the objects have been removed or not −

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

This will produce the following output −

{
   "_id" : ObjectId("5cc7f9f88f9e6ff3eb0ce446"),
   "UserName" : "Larry",
   "UserDetails" : [
      {
         "_id" : 101,
         "UserEmailId" : "976Larry@gmail.com"
      }
   ]
}
{
   "_id" : ObjectId("5cc7f9f98f9e6ff3eb0ce447"),
   "UserName" : "Mike",
   "UserDetails" : [ ]
}
raja
Published on 21-May-2019 12:20:11
Advertisements