MongoDB query to replace value with aggregation?


Use aggregate framework along with $literal operator. Let us first create a collection with documents −

> db.replaceValueDemo.insertOne(
   {
      _id : 100,
      "EmployeeName" :"Chris",
      "EmployeeOtherDetails": {
         "EmployeeDesignation" : "HR",
         "EmployeeAge":27
      }
   }
);
{ "acknowledged" : true, "insertedId" : 100 }
> db.replaceValueDemo.insertOne(
   {
      _id : 101,
      "EmployeeName" :"David",
      "EmployeeOtherDetails": {
         "EmployeeDesignation" : "Tester",
         "EmployeeAge":26
      }
   }
);
{ "acknowledged" : true, "insertedId" : 101 }

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

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

This will produce the following output −

{
   "_id" : 100,
   "EmployeeName" : "Chris",
   "EmployeeOtherDetails" : {
      "EmployeeDesignation" : "HR",
      "EmployeeAge" : 27
   }
}
{
   "_id" : 101,
   "EmployeeName" : "David",
   "EmployeeOtherDetails" : {
      "EmployeeDesignation" : "Tester",
      "EmployeeAge" : 26
   }
}

Following is the query to replace a value −

> db.replaceValueDemo.aggregate([{
   "$project": {
      "_id": 1,
      "EmployeeOtherDetails": {
         EmployeeAge: 1,
         EmployeeDesignation : { $literal: "Developer" }
      }
   }
}]);

This will produce the following output −

{ "_id" : 100, "EmployeeOtherDetails" : { "EmployeeAge" : 27, "EmployeeDesignation" : "Developer" } }
{ "_id" : 101, "EmployeeOtherDetails" : { "EmployeeAge" : 26, "EmployeeDesignation" : "Developer" } }

Updated on: 30-Jul-2019

352 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements