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

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

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

问题

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

  1. {
  2. "VehicleDetailId": 1,
  3. "VehicleDetail": [
  4. {
  5. "Id": 1,
  6. "Make": "BMW"
  7. },
  8. {
  9. "Id": 1,
  10. "Model": "ABDS"
  11. },
  12. {
  13. "Id": 1,
  14. "Trim": "5.6L/ASMD"
  15. },
  16. {
  17. "Id": 1,
  18. "Year": 2008
  19. }
  20. ]
  21. }

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

  1. {
  2. "Id": 1,
  3. "Model": "ABDS"
  4. }

或者第三个元素,

  1. {
  2. "Id": 1,
  3. "Trim": "5.6L/ASMD"
  4. }

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

英文:

Suppose I have a document with the following structure,

  1. {
  2. "VehicleDetailId": 1,
  3. "VehicleDetail": [
  4. {
  5. "Id": 1,
  6. "Make": "BMW"
  7. },
  8. {
  9. "Id": 1,
  10. "Model": "ABDS"
  11. },
  12. {
  13. "Id": 1,
  14. "Trim": "5.6L/ASMD"
  15. },
  16. {
  17. "Id": 1,
  18. "Year": 2008
  19. }
  20. ]
  21. }

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.,

  1. {
  2. "Id": 1,
  3. "Model": "ABDS"
  4. }

or the third,

  1. {
  2. "Id": 1,
  3. "Trim": "5.6L/ASMD"
  4. }

How should I write the query to achieve this?

答案1

得分: 1

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

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

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

输出:

  1. {
  2. "SecondElement": [
  3. {
  4. "Id": 1,
  5. "Model": "ABDS"
  6. }
  7. ]
  8. }
英文:

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.

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

Output:

  1. {
  2. "SecondElement": [
  3. {
  4. "Id": 1,
  5. "Model": "ABDS"
  6. }
  7. ]
  8. }

答案2

得分: 0

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

  1. 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

  1. 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:

确定