DocumentDB SQL - 数组创建



在 DocumentDB SQL 中,Microsoft 添加了一个关键功能,我们可借助它轻松创建数组。这表示当我们运行查询时,作为查询结果,它将创建一个类似于 JSON 对象的集合数组。

让我们考虑与之前示例中相同的文档。

AndersenFamily 文档如下。

{ 
   "id": "AndersenFamily", 
   "lastName": "Andersen",
	
   "parents": [ 
      { "firstName": "Thomas", "relationship":  "father" }, 
      { "firstName": "Mary Kay", "relationship":  "mother" } 
   ], 
   
   "children": [ 
      { 
         "firstName": "Henriette Thaulow", 
         "gender": "female", 
         "grade": 5, 
         "pets": [ { "givenName": "Fluffy", "type":  "Rabbit" } ] 
      } 
   ],
   
   "location": { "state": "WA", "county": "King", "city": "Seattle" }, 
   "isRegistered": true 
} 

SmithFamily 文档如下。

{ 
   "id": "SmithFamily", 
	
   "parents": [ 
      { "familyName": "Smith", "givenName": "James" }, 
      { "familyName": "Curtis", "givenName": "Helen" } 
   ],
   
   "children": [ 
      {
         "givenName": "Michelle", 
         "gender": "female", 
         "grade": 1 
      },
		
      { 
         "givenName": "John", 
         "gender": "male", 
         "grade": 7,
			
         "pets": [ 
            { "givenName": "Tweetie", "type": "Bird" } 
         ] 
      } 
   ], 
   
   "location": { 
      "state": "NY", 
      "county": "Queens", 
      "city": "Forest Hills" 
   },
   
   "isRegistered": true 
}

WakefieldFamily 文档如下。

{ 
   "id": "WakefieldFamily", 
	
   "parents": [ 
      { "familyName": "Wakefield", "givenName": "Robin" }, 
      { "familyName": "Miller", "givenName": "Ben" } 
   ],
   
   "children": [ 
      { 
         "familyName": "Merriam", 
         "givenName": "Jesse", 
         "gender": "female", 
         "grade": 6,
			
         "pets": [ 
            { "givenName": "Charlie Brown", "type": "Dog" }, 
            { "givenName": "Tiger", "type": "Cat" }, 
            { "givenName": "Princess", "type": "Cat" }
         ]
      },
		
      { 
         "familyName": "Miller", 
         "givenName": "Lisa", 
         "gender": "female", 
         "grade": 3,
			
         "pets": [ 
            { "givenName": "Jake", "type": "Snake" } 
         ] 
      } 
   ], 
   
   "location": { "state": "NY", "county": "Manhattan", "city": "NY" }, 
   "isRegistered": false 
}

我们来看一个示例。

Array Creation

下文是一个查询,它将返回每个家庭的家庭名称和地址。

SELECT f.id AS FamilyName, 
[f.location.city, f.location.county, f.location.state] AS Address 
FROM Families f

正如你所见,city、county 和 state 字段包含在方括号中,这将创建一个数组,此数组名为 Address。当执行上述查询时,它产生以下输出。

[ 
   { 
      "FamilyName": "WakefieldFamily", 
      "Address": [ 
         "NY", 
         "Manhattan", 
         "NY" 
      ] 
   },
	
   { 
      "FamilyName": "SmithFamily", 
      "Address": [
         "Forest Hills", 
         "Queens", 
         "NY" 
      ] 
   },
	
   { 
      "FamilyName": "AndersenFamily", 
      "Address": [ 
         "Seattle", 
         "King", 
         "WA" 
      ] 
   } 
]

city、county 和 state 信息已添加到上述输出中的 Address 数组。

广告