Documentdb Sql 简明教程

DocumentDB SQL - Scalar Expressions

在 DocumentDB SQL 中,SELECT 子句还支持标量表达式,如常量、算术表达式、逻辑表达式等。通常,标量查询很少使用,因为它们不会实际查询集合中的文档,只是评估表达式。但使用标量表达式查询来学习基础知识、如何在查询中使用表达式和塑造 JSON,仍然很有帮助,并且这些概念直接适用于在集合中的文档中所运行的实际查询。

In DocumentDB SQL, the SELECT clause also supports scalar expressions like constants, arithmetic expressions, logical expressions, etc. Normally, scalar queries are rarely used, because they don’t actually query documents in the collection, they just evaluate expressions. But it’s still helpful to use scalar expression queries to learn the basics, how to use expressions and shape JSON in a query, and these concepts apply directly to the actual queries you’ll be running against documents in a collection.

让我们来看一个包含多个标量查询的示例。

Let’s take a look at an example which contains multiple scalar queries.

scalar queries

在查询浏览器中,只选择要执行的文本并单击“运行”。我们先运行第一个。

In the Query Explorer, select just the text to be executed and click ‘Run’. Let’s run this first one.

SELECT "Hello"

执行以上查询后,将产生以下输出。

When the above query is executed, it produces the following output.

[
   {
      "$1": "Hello"
   }
]

此输出可能看起来有些令人困惑,因此我们来将其分解一下。

This output may look a bit confusing, so let’s break it down.

  1. First, as we saw in the last demo, query results are always contained in square brackets because they are returned as a JSON array, even results from scalar expression queries like this one that only returns a single document.

  2. We have an array with one document in it, and that document has a single property in it for the single expression in the SELECT statement.

  3. The SELECT statement doesn’t provide a name for this property, thus DocumentDB auto generates one using $1.

  4. This is usually not what we want, which is why we can use AS to alias the expression in the query, which sets the property name in the generated document the way you’d like it to be, word, in this example.

SELECT "Hello" AS word

执行以上查询后,将产生以下输出。

When the above query is executed, it produces the following output.

[
   {
      "word": "Hello"
   }
]

同样,以下是一个简单的查询。

Similarly, following is another simple query.

SELECT ((2 + 11 % 7)-2)/3

查询检索以下输出。

The query retrieves the following output.

[
   {
      "$1": 1.3333333333333333
   }
]

让我们再看另一个嵌套数组和嵌入对象的塑造示例。

Let’s take a look at another example of shaping nested arrays and embedded objects.

SELECT
   {
      "words1":
         ["Hello", "World"],
      "words2":
         ["How", "Are", "You?"]
   } AS allWords

执行以上查询后,将产生以下输出。

When the above query is executed, it produces the following output.

[
   {
      "allWords": {
         "words1": [
            "Hello",
            "World"
         ],

         "words2": [
            "How",
            "Are",
            "You?"
         ]
      }
   }
]