首页 文章

从CosmosDB中的文档嵌套数组中的对象中选择值

提问于
浏览
1

想象一下,我们有一个这样的集合(例子取自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] 我试过 [][$] 但是不起作用

有人知道如何以简单的方式解决这个问题吗?

2 回答

  • 0

    您可以使用ARRAY(子查询)表达式来实现此目的 . 这是查询:

    SELECT
        food.id,
        ARRAY(SELECT serving.description FROM serving IN food.servings) AS servings
    FROM food
    WHERE food.id = "19015"
    
  • 3

    通过执行此查询:从food.servings中的食品加入服务中选择food.id,servings.description

    你至少会得到以下结果:

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

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

相关问题