Tutorialspoint

1 Answer
Anvi Jain

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" } }

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.