如何从CosmosDB文档中的特定位置检索数组元素?

huangapple go评论67阅读模式
英文:

How to retrieve array element from a specific position in CosmosDB document?

问题

假设我有一个具有以下结构的文档:

{
    "VehicleDetailId": 1,
    "VehicleDetail": [
        {
            "Id": 1,
            "Make": "BMW"
        },
        {
            "Id": 1,
            "Model": "ABDS"
        },
        {
            "Id": 1,
            "Trim": "5.6L/ASMD"
        },
        {
            "Id": 1,
            "Year": 2008
        }
    ]
}

现在我想从VehicleDetail数组中检索位于特定位置的数组元素,比如我想检索第二个元素,即:

{
    "Id": 1,
    "Model": "ABDS"
}

或者第三个元素,

{
    "Id": 1,
    "Trim": "5.6L/ASMD"
}

我应该如何编写查询来实现这个目标?

英文:

Suppose I have a document with the following structure,

{
    "VehicleDetailId": 1,
    "VehicleDetail": [
        {
            "Id": 1,
            "Make": "BMW"
        },
        {
            "Id": 1,
            "Model": "ABDS"
        },
        {
            "Id": 1,
            "Trim": "5.6L/ASMD"
        },
        {
            "Id": 1,
            "Year": 2008
        }
    ]
}

Now I want to retrieve an array element located at a specific position from VehicleDetail array like I want to retrieve the second element, i.e.,

{
    "Id": 1,
    "Model": "ABDS"
}

or the third,

{
    "Id": 1,
    "Trim": "5.6L/ASMD"
}

How should I write the query to achieve this?

答案1

得分: 1

使用内置的ARRAY_SLICE函数。这允许您选择数组的一部分。

传递数组、起始位置和要选择的元素数量。

SELECT ARRAY_SLICE(c.VehicleDetail, 1, 1) As SecondElement
FROM c

输出:

{
    "SecondElement": [
        {
            "Id": 1,
            "Model": "ABDS"
        }
    ]
}
英文:

Use the built-in ARRAY_SLICE function. This allows you to select part of an array.

Pass the array, starting position, number of elements to select.

SELECT ARRAY_SLICE(c.VehicleDetail, 1, 1) As SecondElement
FROM c

Output:

{
	"SecondElement": [
		{
			"Id": 1,
			"Model": "ABDS"
		}
	]
}

答案2

得分: 0

根据其他人的建议,可以使用ARRAY_SLICE。如果您想要选择数组中的特定元素,我们可以结合使用ARRAY_SLICE和ARRAY函数。

SELECT ARRAY_SLICE((ARRAY(SELECT a.Id FROM a IN c.VehicleDetail)), 1, 1) as SecondElement FROM c
英文:

As suggested by others, ARRAY_SLICE can be used. If you want to select specific element in array, we can combine ARRAY_SLICE and ARRAY functions

SELECT ARRAY_SLICE((ARRAY(SELECT a.Id FROM a IN c.VehicleDetail)), 1, 1) as SecondElement FROM c

huangapple
  • 本文由 发表于 2020年1月6日 17:55:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/59609937.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定