Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return dynamic values while project stage in mongo aggregation

I wanted to structure my response object while project stage of aggregation. But I am facing problem to concat a string with another key value.
Here is my aggregation return object

[
  {
    "total_price": 8.92,
    "paymentStatus": "Paid",
    "refundedAmount": 5
  },
  {
    "total_price": 20.92,
    "paymentStatus": "Paid",
    "refundedAmount": 15
  }
]

But I want to return as a 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"
          }
        ]
      }
    }
  }
])

Sample Mongo Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading