5

假设我们有一个这样的集合(示例取自 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
        }
    ]
}

我如何在 SQL api 中查询 CosmosDB 以获得这样的结果?

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

在 MongoDB 我会使用这样的查询

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

通过连接等尝试了多个场景

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

或者

SELECT 
    food.id,
    [{
        description: food.servings[0].description
    }] AS servings
FROM food
WHERE food.id = "19015"
  • 而不是[0]我尝试过[][$]但不起作用

有人知道我可以如何简单地解决这个问题吗?

4

2 回答 2

9

您可以使用 ARRAY(subquery) 表达式来实现这一点。这是查询:

SELECT
    food.id,
    ARRAY(SELECT serving.description FROM serving IN food.servings) AS servings
FROM food
WHERE food.id = "19015"
于 2018-07-20T20:27:40.047 回答
1

通过执行此查询:

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

你至少会得到以下结果:

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

不是 100% 你所期望的,但也许是你可以使用的东西!

于 2018-07-20T12:41:13.517 回答