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
How to add a field with static value to MongoDB find query?
To add a field with static value to MongoDB find query, use the $literal operator with the aggregation framework. The $literal operator returns a value without parsing, making it perfect for adding constant values to query results.
Syntax
db.collection.aggregate([
{
$project: {
field1: 1,
field2: 1,
"staticFieldName": { $literal: "staticValue" }
}
}
]);
Sample Data
db.fieldWithStaticValue.insertMany([
{"Name": "Larry", "Age": 24},
{"Name": "Chris", "Age": 23},
{"Name": "David", "Age": 26}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd6554c7924bb85b3f48948"),
ObjectId("5cd655567924bb85b3f48949"),
ObjectId("5cd655607924bb85b3f4894a")
]
}
View Original Data
db.fieldWithStaticValue.find();
{ "_id": ObjectId("5cd6554c7924bb85b3f48948"), "Name": "Larry", "Age": 24 }
{ "_id": ObjectId("5cd655567924bb85b3f48949"), "Name": "Chris", "Age": 23 }
{ "_id": ObjectId("5cd655607924bb85b3f4894a"), "Name": "David", "Age": 26 }
Example: Add Static Numeric Value
db.fieldWithStaticValue.aggregate([
{
$project: {
Name: 1,
Age: 1,
"StaticValue": { $literal: 100 }
}
}
]);
{ "_id": ObjectId("5cd6554c7924bb85b3f48948"), "Name": "Larry", "Age": 24, "StaticValue": 100 }
{ "_id": ObjectId("5cd655567924bb85b3f48949"), "Name": "Chris", "Age": 23, "StaticValue": 100 }
{ "_id": ObjectId("5cd655607924bb85b3f4894a"), "Name": "David", "Age": 26, "StaticValue": 100 }
Example: Add Static String Value
db.fieldWithStaticValue.aggregate([
{
$project: {
Name: 1,
Age: 1,
"Department": { $literal: "Engineering" }
}
}
]);
{ "_id": ObjectId("5cd6554c7924bb85b3f48948"), "Name": "Larry", "Age": 24, "Department": "Engineering" }
{ "_id": ObjectId("5cd655567924bb85b3f48949"), "Name": "Chris", "Age": 23, "Department": "Engineering" }
{ "_id": ObjectId("5cd655607924bb85b3f4894a"), "Name": "David", "Age": 26, "Department": "Engineering" }
Key Points
-
$literalcan add any static value - numbers, strings, objects, or arrays. - Use
$projectstage to include existing fields (1) and define new static fields. - This approach works with the aggregation framework, not traditional
find()queries.
Conclusion
The $literal operator in MongoDB's aggregation pipeline allows you to add fields with constant values to query results. Use it within $project stages to enhance documents with static data during retrieval.
Advertisements
