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 fields in MongoDB?
To concatenate fields in MongoDB, use the $concat operator within an aggregation pipeline. This operator combines multiple string values into a single string, with optional separators between them.
Syntax
db.collection.aggregate([
{
$project: {
"newField": {
$concat: ["$field1", "separator", "$field2"]
}
}
}
]);
Sample Data
db.concatenateFieldsDemo.insertMany([
{"StudentFirstName": "Adam", "StudentLastName": "Smith"},
{"StudentFirstName": "John", "StudentLastName": "Doe"},
{"StudentFirstName": "David", "StudentLastName": "Miller"},
{"StudentFirstName": "Sam", "StudentLastName": "Williams"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd6ebf46d78f205348bc62e"),
ObjectId("5cd6ebfc6d78f205348bc62f"),
ObjectId("5cd6ec376d78f205348bc630"),
ObjectId("5cd6ec436d78f205348bc631")
]
}
Example: Concatenate First and Last Names
Let's concatenate the first and last names with a "/" separator ?
db.concatenateFieldsDemo.aggregate([
{
$project: {
"StudentFullName": {
$concat: ["$StudentFirstName", "/", "$StudentLastName"]
},
"StudentFirstName": 1,
"StudentLastName": 1
}
}
]);
{ "_id": ObjectId("5cd6ebf46d78f205348bc62e"), "StudentFirstName": "Adam", "StudentLastName": "Smith", "StudentFullName": "Adam/Smith" }
{ "_id": ObjectId("5cd6ebfc6d78f205348bc62f"), "StudentFirstName": "John", "StudentLastName": "Doe", "StudentFullName": "John/Doe" }
{ "_id": ObjectId("5cd6ec376d78f205348bc630"), "StudentFirstName": "David", "StudentLastName": "Miller", "StudentFullName": "David/Miller" }
{ "_id": ObjectId("5cd6ec436d78f205348bc631"), "StudentFirstName": "Sam", "StudentLastName": "Williams", "StudentFullName": "Sam/Williams" }
Key Points
-
$concatonly works with string values − non-string fields must be converted first using$toString. - Use
$projectto include original fields (value1) along with the concatenated field. - Common separators include spaces
" ", hyphens"-", or slashes"/".
Conclusion
The $concat operator in MongoDB aggregation pipelines effectively combines multiple string fields into one. Use it within $project to create new concatenated fields while preserving original data.
Advertisements
