I wanted to structure my response object in the project stage of aggregation. But I am facing a problem in concatenating a string with another key value.
Here is my aggregation return result:
[
{
"total_price": 8.92,
"paymentStatus": "Paid",
"refundedAmount": 5
},
{
"total_price": 20.92,
"paymentStatus": "Paid",
"refundedAmount": 15
}
]
But I want to return the result as the structure of:
[
{
"total_price": 8.92,
"paymentStatus": "Paid",
"refundedAmount": 5,
"description": "Refunded 5"
},
{
"total_price": 20.92,
"paymentStatus": "Paid",
"refundedAmount": 15,
"description": "Refunded 15"
}
]
Here totalPrice, paymentStatus and refundedAmount are available in database. I want to add a key called description while project.
CodePudding user response:
You need $concat
operator and convert refundedAmount
to string.
db.collection.aggregate([
{
"$project": {
total_price: 1,
paymentStatus: 1,
refundedAmount: 1,
description: {
$concat: [
"Refunded ",
{
$toString: "$refundedAmount"
}
]
}
}
}
])