azureazure-cosmosdbazure-cosmosdb-sqlapi

CosmosDB NoSQL Select Multiple Values


If I have data that looks like :

{"Test": {
 "Id":123
 "Name": "Sam",
 "Age": "27"
 }
}

How do I output "Sam: 27"

I have tried

SELECT VALUE {c.Test.Name: c.Test.Age}
FROM c where c.Test.Id = '123'

Solution

  • Typically you would just return the properties (and values) you need and format output in your code, so you’d change your query to something like:

    SELECT c.Test.Name AS Name, c.Test.Age AS Age
    FROM c
    WHERE c.Test.Id = 123
    

    Which returns something like

    [
      {
        “Name” : “Sam”,
        “Age” : “27”
      }
    ]
    

    However - if you truly want to return custom output, then you could concatenate values into a new output value:

    SELECT VALUE {
      customtext: CONCAT(c.Test.Name, “: “, c.Test.Age)
    }
    FROM c
    WHERE c.Test.Id = 123
    

    which returns something like:

    [
        {
            "combined": "Sam: 27"
        }
    ]
    

    And lastly, if you don't even want property names, you can output just the value, like this:

    SELECT VALUE CONCAT(c.Test.Name,': ', c.Test.Age) 
    FROM c
    WHERE c.Test.Id = 123
    

    which returns:

    [
        "Sam: 27"
    ]