$concat
The $concat operator joins strings together into a single string.
📌 Syntax
{ "$concat": [ <expression1>, <expression2>, ... ] }
All expressions must resolve to strings. If any operand resolves to null, the result is null.
✅ Base Example 1 – Full Name
📥 Input Document
{ "firstName": "Jane", "lastName": "Doe" }
📌 Expression
{ "$concat": ["$firstName", " ", "$lastName"] }
📤 Output
"Jane Doe"
✅ Base Example 2 – File Path Builder
📥 Input Document
{ "folder": "invoices", "file": "2025.pdf" }
📌 Expression
{ "$concat": ["/data/", "$folder", "/", "$file"] }
📤 Output
"/data/invoices/2025.pdf"
🧱 Ecommerce Example – Generate SKU Code
📌 Pipeline
[
{ "$unwind": "$items" },
{
"$project": {
"sku": {
"$concat": [
"$items.category", "-",
"$items.brand", "-",
"$items.productId"
]
}
}
}
]
📥 Input Document
{
"items": [
{
"productId": "X123",
"category": "ELEC",
"brand": "SNY"
},
{
"productId": "Y987",
"category": "BOOK",
"brand": "PNH"
}
]
}
📤 Output
[
{ "sku": "ELEC-SNY-X123" },
{ "sku": "BOOK-PNH-Y987" }
]
🔧 Common Use Cases
- Formatting names and addresses
- Constructing SKUs or file paths
- HTML or CSV generation
🔗 Related Operators
$toString,$substr,$toLower,$trim$project,$set,$map
🧠Notes
- Ensure all values are strings or cast them using
$toString. - Use
$condor$ifNullto avoid null operands.