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 prepend string to entire column in MongoDB?
To prepend a string to an entire column in MongoDB, use the $concat operator within the aggregation framework. The $concat operator combines the prepend string with the existing field value.
Syntax
db.collection.aggregate([
{
$project: {
"fieldName": {
$concat: ["prependString", "$fieldName"]
}
}
}
]);
Sample Data
db.prependDemo.insertMany([
{"StudentFirstName": "John"},
{"StudentFirstName": "Chris"},
{"StudentFirstName": "Robert"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ccf3bcedceb9a92e6aa1955"),
ObjectId("5ccf3bd3dceb9a92e6aa1956"),
ObjectId("5ccf3bd8dceb9a92e6aa1957")
]
}
Display the documents to verify the data ?
db.prependDemo.find();
{ "_id": ObjectId("5ccf3bcedceb9a92e6aa1955"), "StudentFirstName": "John" }
{ "_id": ObjectId("5ccf3bd3dceb9a92e6aa1956"), "StudentFirstName": "Chris" }
{ "_id": ObjectId("5ccf3bd8dceb9a92e6aa1957"), "StudentFirstName": "Robert" }
Example: Prepend "Mr." to StudentFirstName
db.prependDemo.aggregate([
{
$project: {
"StudentFirstName": {
$concat: ["Mr.", "$StudentFirstName"]
}
}
}
]);
{ "_id": ObjectId("5ccf3bcedceb9a92e6aa1955"), "StudentFirstName": "Mr.John" }
{ "_id": ObjectId("5ccf3bd3dceb9a92e6aa1956"), "StudentFirstName": "Mr.Chris" }
{ "_id": ObjectId("5ccf3bd8dceb9a92e6aa1957"), "StudentFirstName": "Mr.Robert" }
Key Points
-
$concatcreates a new string by joining multiple strings in order -
$projectstage reshapes documents with the modified field - Original data remains unchanged − this only transforms the output
Conclusion
Use $concat within $project to prepend strings to column values in MongoDB. This approach preserves original data while displaying transformed results in the aggregation pipeline output.
Advertisements
