Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" } }Advertisements