How do I add a field to existing record in MongoDB?


You can use update command to add a field to existing record. Let us first create a collection with documents −

> db.addAFieldToEveryRecordDemo.insertOne({"ClientName":"Chris","ClientAge":34});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd00e32588d4a6447b2e061")
}
> db.addAFieldToEveryRecordDemo.insertOne({"ClientName":"Robert","ClientAge":36});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd00e59588d4a6447b2e062")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cd00e32588d4a6447b2e061"),
   "ClientName" : "Chris",
   "ClientAge" : 34
}
{
   "_id" : ObjectId("5cd00e59588d4a6447b2e062"),
   "ClientName" : "Robert",
   "ClientAge" : 36
}

Here is the query to add a field to every record. We are adding ClientDetails −

>db.addAFieldToEveryRecordDemo.update({},{$set:{"ClientDetails.ClientCountryName":""}},true,true);
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

Let us check all documents have been added with new record or not −

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

This will produce the following output −

{
   "_id" : ObjectId("5cd00e32588d4a6447b2e061"),
   "ClientName" : "Chris",
   "ClientAge" : 34,
   "ClientDetails" : {
      "ClientCountryName" : ""
   }
}
{
   "_id" : ObjectId("5cd00e59588d4a6447b2e062"),
   "ClientName" : "Robert",
   "ClientAge" : 36,
   "ClientDetails" : {
      "ClientCountryName" : ""
   }
}

Updated on: 30-Jul-2019

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements