想象我们有一个这样的集合(示例取自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]
或[]
而不是[$]
,但没有用有人知道我如何以简单的方式解决此问题?
答案 0 :(得分:5)
您可以使用ARRAY(subquery)表达式来实现此目的。这是查询:
SELECT
food.id,
ARRAY(SELECT serving.description FROM serving IN food.servings) AS servings
FROM food
WHERE food.id = "19015"
答案 1 :(得分:0)
通过执行以下查询: 选择food.id,servings.description 食物中的食物加入食物
您至少会得到以下结果:
{"id":19015, "description":"bar"}
{"id":19015, "description":"bar (1 oz)"}
{"id":19015, "description":"bar"}
不是您所期望的100%,但是也许您可以使用!