Include all existing fields and add new fields to document in MongoDB?


You can achieve this with the help of $addFields operator. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.addFieldDemo.insertOne({"EmployeeId":101,"EmployeeName":"Larry","EmployeeDetails":{
   "EmployeeSalary":65000,"EmployeeCity":"New York","Message":"Hi"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f654d8d10a061296a3c44")
}

Display all documents from a collection with the help of find() method. The query is as follows −

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

The following is the output −

{
   "_id" : ObjectId("5c7f654d8d10a061296a3c44"),
   "EmployeeId" : 101,
   "EmployeeName" : "Larry",
   "EmployeeDetails" : {
      "EmployeeSalary" : 65000,
      "EmployeeCity" : "New York",
      "Message" : "Hi"
   }
}

Here is the query to include all existing fields and add new fields to document in MongoDB −

> db.addFieldDemo.aggregate([ { "$addFields": { "EmployeeBasicSalary":"$EmployeeDetails.EmployeeSalary" } } ]).pretty();

The following is the output −

{
   "_id" : ObjectId("5c7f654d8d10a061296a3c44"),
   "EmployeeId" : 101,
   "EmployeeName" : "Larry",
   "EmployeeDetails" : {
      "EmployeeSalary" : 65000,
      "EmployeeCity" : "New York",
      "Message" : "Hi"
   },
   "EmployeeBasicSalary" : 65000
}

Look at the sample output, “EmployeeBasicSalary” has been added.

Updated on: 30-Jul-2019

305 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements