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

Convert array of objects to string

I am having a MongoDB aggregate result:

{
    "healthDetails": [
        {
          "problem": "Fever",
          "note": "normal"
        },
        {
          "problem": "Allergy",
          "note": "critical"
        }
      ]
}

I need to convert the above array like this:

{
    "healthDetails": "Fever - normal, Allergy - critical"
}

Need to remove square brackets and double quotes and concat the values by comma-separated.

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

How to do that in MongoDB projection?

Need some valuable help.

>Solution :

Work with aggregation pipeline.

  1. $reduce – Iterate the elements in the healthDetails array and transform into the string by concatenating the value with $concat.

  2. $trim – Remove the beginning and ending characters for ", " from the result generated in 1.

db.collection.aggregate([
  {
    $set: {
      "healthDetails": {
        $trim: {
          input: {
            $reduce: {
              input: "$healthDetails",
              initialValue: "",
              in: {
                $concat: [
                  "$$value",
                  ", ",
                  {
                    $concat: [
                      "$$this.problem",
                      " - ",
                      "$$this.note"
                    ]
                  }
                ]
              }
            }
          },
          chars: ", "
        }
      }
    }
  }
])

Demo @ 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