Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB query to replace value with aggregation?
To replace values in MongoDB using aggregation, use the $project stage with the $literal operator. The $literal operator returns a specified value without interpreting it as an expression, making it perfect for replacing field values with static content.
Syntax
db.collection.aggregate([
{
$project: {
fieldName: { $literal: "newValue" },
otherField: 1
}
}
]);
Sample Data
db.replaceValueDemo.insertMany([
{
_id: 100,
"EmployeeName": "Chris",
"EmployeeOtherDetails": {
"EmployeeDesignation": "HR",
"EmployeeAge": 27
}
},
{
_id: 101,
"EmployeeName": "David",
"EmployeeOtherDetails": {
"EmployeeDesignation": "Tester",
"EmployeeAge": 26
}
}
]);
{ "acknowledged": true, "insertedIds": { "0": 100, "1": 101 } }
Example: Replace Designation with Fixed Value
Replace all employee designations with "Developer" while keeping other fields ?
db.replaceValueDemo.aggregate([
{
$project: {
"_id": 1,
"EmployeeName": 1,
"EmployeeOtherDetails": {
"EmployeeAge": "$EmployeeOtherDetails.EmployeeAge",
"EmployeeDesignation": { $literal: "Developer" }
}
}
}
]);
{ "_id": 100, "EmployeeName": "Chris", "EmployeeOtherDetails": { "EmployeeAge": 27, "EmployeeDesignation": "Developer" } }
{ "_id": 101, "EmployeeName": "David", "EmployeeOtherDetails": { "EmployeeAge": 26, "EmployeeDesignation": "Developer" } }
Key Points
-
$literaltreats the value as a constant, not an expression or field reference. - Use
1to include existing fields unchanged. - Nested field replacement requires reconstructing the parent object structure.
Conclusion
The $literal operator in aggregation pipelines effectively replaces field values with static content. This approach is ideal when you need to transform data without modifying the original collection.
Advertisements
