6

Imagine we have a such collection (example taken from https://www.documentdb.com/sql/demo)

{
    "_id" : "19015",
    "description" : "Snacks, granola bars, hard, plain",
    "servings" : [ 
        {
            "amount" : 1,
            "description" : "bar",
            "weightInGrams" : 21
        }, 
        {
            "amount" : 1,
            "description" : "bar (1 oz)",
            "weightInGrams" : 28
        }, 
        {
            "amount" : 1,
            "description" : "bar",
            "weightInGrams" : 25
        }
    ]
}

How i can query CosmosDB in SQL api to get results such like this?

{
    "_id" : "19015",
    "servings" : [ 
        {
            "description" : "bar"
        }, 
        {
            "description" : "bar (1 oz)"
        }, 
        {
            "description" : "bar"
        }
    ]
}

at MongoDB i would use such query

db.getCollection('food').find({id: '19015'}, {'servings.description' : 1})

Tried multiple scenarious with joins etc

SELECT 
    food.id,
    food.servings.description
FROM food
WHERE food.id = "19015"

or

SELECT 
    food.id,
    [{
        description: food.servings[0].description
    }] AS servings
FROM food
WHERE food.id = "19015"
  • instead of [0] i tried [] or [$] but doesn't works

Does somebody has idea how in simply way i can resolve this issue?

1

2 Answers 2

12

You could use the ARRAY(subquery) expression to achieve this. Here's the query:

SELECT
    food.id,
    ARRAY(SELECT serving.description FROM serving IN food.servings) AS servings
FROM food
WHERE food.id = "19015"
Sign up to request clarification or add additional context in comments.

2 Comments

So, there are subqueries now in CosmosDB. Any pointers regarding documentation?
Yes, Cosmos DB recently added support for subqueries. We're currently working on publishing the documentation.
1

By executing this query:

select food.id, servings.description
from food join servings in food.servings

you would at least get the following result:

{"id":19015, "description":"bar"}
{"id":19015, "description":"bar (1 oz)"}
{"id":19015, "description":"bar"}

Not 100% what you were expecting, but maybe something you can work with!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.