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
Concatenate strings from two fields into a third field in MongoDB?
To concatenate strings from two fields into a third field in MongoDB, use the $concat operator within an aggregation pipeline with $project stage.
Syntax
db.collection.aggregate([
{ $project: { "newFieldName": { $concat: [ "$field1", "delimiter", "$field2" ] } } }
]);
Sample Data
db.concatenateStringsDemo.insertMany([
{"StudentFirstName": "John", "StudentLastName": "Doe"},
{"StudentFirstName": "John", "StudentLastName": "Smith"},
{"StudentFirstName": "Carol", "StudentLastName": "Taylor"},
{"StudentFirstName": "David", "StudentLastName": "Miller"},
{"StudentFirstName": "James", "StudentLastName": "Williams"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c9bb7362d66697741252444"),
ObjectId("5c9bb7402d66697741252445"),
ObjectId("5c9bb74c2d66697741252446"),
ObjectId("5c9bb7752d66697741252447"),
ObjectId("5c9bb7862d66697741252448")
]
}
Example: Creating Full Name Field
Let's concatenate "StudentFirstName" and "StudentLastName" into a "StudentFullName" field ?
db.concatenateStringsDemo.aggregate([
{ $project: { "StudentFullName": { $concat: [ "$StudentFirstName", " / ", "$StudentLastName" ] } } }
]);
{ "_id": ObjectId("5c9bb7362d66697741252444"), "StudentFullName": "John / Doe" }
{ "_id": ObjectId("5c9bb7402d66697741252445"), "StudentFullName": "John / Smith" }
{ "_id": ObjectId("5c9bb74c2d66697741252446"), "StudentFullName": "Carol / Taylor" }
{ "_id": ObjectId("5c9bb7752d66697741252447"), "StudentFullName": "David / Miller" }
{ "_id": ObjectId("5c9bb7862d66697741252448"), "StudentFullName": "James / Williams" }
Including Original Fields
To keep the original fields along with the concatenated field ?
db.concatenateStringsDemo.aggregate([
{ $project: {
"StudentFirstName": 1,
"StudentLastName": 1,
"StudentFullName": { $concat: [ "$StudentFirstName", " ", "$StudentLastName" ] }
}}
]);
Key Points
- The
$concatoperator takes an array of strings to concatenate - Field references use
$prefix:"$fieldName" - Add delimiters like spaces or symbols between fields for readability
- Use
fieldName: 1in$projectto include original fields in output
Conclusion
The $concat operator in MongoDB aggregation pipelines efficiently combines multiple string fields into a single field with custom delimiters, making it ideal for creating computed fields like full names or formatted addresses.
Advertisements
