Documentdb 简明教程
DocumentDB - Insert Document
在本教程中,我们将着手处理集合中的实际文档。您可以使用 Azure 门户或 .Net SDK 创建文档。
In this chapter, we will get to work with actual documents in a collection. You can create documents using either Azure portal or .Net SDK.
Creating Documents with the Azure Portal
让我们看一下将文档添加到您的集合的以下步骤。
Let’s take a look at the following steps to add document to your collection.
Step 1 − 在 myfirstdb 中添加新的 S1 定价层的 Families 集合。
Step 1 − Add new collection Families of S1 pricing tier in myfirstdb.

Step 2 − 选择 Families 集合,然后单击“创建文档”选项,打开“新建文档”面板。
Step 2 − Select the Families collection and click on Create Document option to open the New Document blade.

这是一个简单的文本编辑器,它允许您为新文档输入任何 JSON。
This is just a simple text editor that lets you type any JSON for a new document.

Step 3 − 这是原始数据输入,让我们输入我们的第一个文档。
Step 3 − As this is raw data entry, let’s enter our first document.
{
"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
}
当您输入上述文档时,您会看到以下屏幕。
When you enter the above document, you will see the following screen.

请注意,我们已为文档提供了一个 id。id 值总是必需的,而且在同一个集合中的所有其他文档中必须唯一。如果您忽略这一点,那么 DocumentDB 会使用 GUID 或全局唯一标识符自动为您生成一个。
Notice that we’ve supplied an id for the document. The id value is always required, and it must be unique across all other documents in the same collection. When you leave it out then DocumentDB would automatically generate one for you using a GUID or a Globally Unique Identifier.
id 始终是一个字符串,它不能是数字、日期、布尔值或其他对象,也不能超过 255 个字符。
The id is always a string and it can’t be a number, date, Boolean, or another object, and it can’t be longer than 255 characters.
还要注意文档的分层结构,该结构具有一些顶级属性,例如必需的 id 以及 lastName 和 isRegistered,但它还具有嵌套属性。
Also notice the document’s hierarchal structure which has a few top-level properties like the required id, as well as lastName and isRegistered, but it also has nested properties.
例如,parents 属性作为 JSON 数组提供,由方括号表示。我们还为 children 提供了另一个数组,尽管在该示例此数组中只有一个子项。
For instance, the parents property is supplied as a JSON array as denoted by the square brackets. We also have another array for children, even though there’s only one child in the array in this example.
Step 4 − 单击“保存”按钮以保存文档,我们已创建了我们的第一个文档。
Step 4 − Click ‘Save’ button to save the document and we’ve created our first document.
正如您所看到的,我们的 JSON 已经应用了漂亮的格式,该格式将每个属性拆分为单独的行,并用一个空格缩进以传达每个属性的嵌套级别。
As you can see that pretty formatting was applied to our JSON, which breaks up every property on its own line indented with a whitespace to convey the nesting level of each property.

该门户包括一个文档浏览器,所以现在让我们使用它来检索我们刚刚创建的文档。
The portal includes a Document Explorer, so let’s use that now to retrieve the document we just created.

Step 5 − 选择一个数据库和数据库中任何集合,查看该集合中的文档。我们当前只有一个名为 myfirstdb 的数据库,其中包含一个名为 Families 的集合,两者在此处下拉菜单中都已预先选择。
Step 5 − Choose a database and any collection within the database to view the documents in that collection. We currently have just one database named myfirstdb with one collection called Families, both of which have been preselected here in the dropdowns.

默认情况下,文档浏览器会显示集合中未经过滤的文档列表,但您还可以通过 ID 搜索任何特定文档,或根据部分 ID 的通配符搜索搜索多个文档。
By default, the Document Explorer displays an unfiltered list of documents within the collection, but you can also search for any specific document by ID or multiple documents based on a wildcard search of a partial ID.
到目前为止,我们的集合中只有一个文档,我们在以下屏幕上看到了它的 ID,AndersonFamily。
We have only one document in our collection so far, and we see its ID on the following screen, AndersonFamily.
Step 6 − 单击 ID 以查看文档。
Step 6 − Click on the ID to view the document.

Creating Documents with the .NET SDK
众所周知,文档只是另一种类型的资源,并且您已经熟悉如何使用 SDK 处理资源。
As you know that documents are just another type of resource and you’ve already become familiar with how to treat resources using the SDK.
-
The one big difference between documents and other resources is that, of course, they’re schema free.
-
Thus there are a lot of options. Naturally, you can just work JSON object graphs or even raw strings of JSON text, but you can also use dynamic objects that lets you bind to properties at runtime without defining a class at compile time.
-
You can also work with real C# objects, or Entities as they are called, which might be your business domain classes.
让我们在使用 .Net SDK 时开始创建文档。以下是步骤。
Let’s start to create documents using .Net SDK. Following are the steps.
Step 1 − 实例化 DocumentClient,然后我们将查询 myfirstdb 数据库,再查询 MyCollection 集合,我们将此存储在私有变量集合中,以便可以在整个类中访问它。
Step 1 − Instantiate DocumentClient then we will query for the myfirstdb database and then query for the MyCollection collection, which we store in this private variable collection so that it’s accessible throughout the class.
private static async Task CreateDocumentClient() {
// Create a new instance of the DocumentClient
using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id =
'myfirstdb'").AsEnumerable().First();
collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,
"SELECT * FROM c WHERE c.id = 'MyCollection'").AsEnumerable().First();
await CreateDocuments(client);
}
}
Step 2 − 在 CreateDocuments 任务中创建一些文档。
Step 2 − Create some documents in CreateDocuments task.
private async static Task CreateDocuments(DocumentClient client) {
Console.WriteLine();
Console.WriteLine("**** Create Documents ****");
Console.WriteLine();
dynamic document1Definition = new {
name = "New Customer 1", address = new {
addressType = "Main Office",
addressLine1 = "123 Main Street",
location = new {
city = "Brooklyn", stateProvinceName = "New York"
}, postalCode = "11229", countryRegionName = "United States"
},
};
Document document1 = await CreateDocument(client, document1Definition);
Console.WriteLine("Created document {0} from dynamic object", document1.Id);
Console.WriteLine();
}
第一个文档将由此动态对象生成。这可能看起来像 JSON,但当然不是。这是 C# 代码,我们正在创建一个真正的 .NET 对象,但没有类定义。相反,属性是从对象初始化方式中推断出来的。
The first document will be generated from this dynamic object. This might look like JSON, but of course it isn’t. This is C# code and we’re creating a real .NET object, but there’s no class definition. Instead, the properties are inferred from the way the object is initialized.
请注意,我们没有为此文档提供 Id 属性。
Notice that we haven’t supplied an Id property for this document.
现在,让我们看一下 CreateDocument。它看起来像我们为创建数据库和集合而看到的相同模式。
Now let’s have a look into CreateDocument. It looks like the same pattern we saw for creating databases and collections.
private async static Task<Document> CreateDocument(DocumentClient client,
object documentObject) {
var result = await client.CreateDocumentAsync(collection.SelfLink, documentObject);
var document = result.Resource;
Console.WriteLine("Created new document: {0}\r\n{1}", document.Id, document);
return result;
}
Step 3 − 这一次,我们调用 CreateDocumentAsync 来指定要向其中添加文档的集合的 SelfLink。我们返回一个具有 resource 属性的响应,在这种情况下,它表示具有系统生成属性的新文档。
Step 3 − This time we call CreateDocumentAsync specifying the SelfLink of the collection we want to add the document to. We get back a response with a resource property that, in this case, represents the new document with its system-generated properties.
Document 对象是 SDK 中的已定义类,它继承自 resource,因此它具有所有常见的 resource 属性,但也包括定义无架构文档本身的动态属性。
The Document object is a defined class in the SDK that inherits from resource and so it has all the common resource properties, but it also includes the dynamic properties that define the schema-free document itself.
private async static Task CreateDocuments(DocumentClient client) {
Console.WriteLine();
Console.WriteLine("**** Create Documents ****");
Console.WriteLine();
dynamic document1Definition = new {
name = "New Customer 1", address = new {
addressType = "Main Office",
addressLine1 = "123 Main Street",
location = new {
city = "Brooklyn", stateProvinceName = "New York"
}, postalCode = "11229", countryRegionName = "United States"
},
};
Document document1 = await CreateDocument(client, document1Definition);
Console.WriteLine("Created document {0} from dynamic object", document1.Id);
Console.WriteLine();
}
当以上代码编译并执行时,您将收到以下输出。
When the above code is compiled and executed you will receive the following output.
**** Create Documents ****
Created new document: 34e9873a-94c8-4720-9146-d63fb7840fad {
"name": "New Customer 1",
"address": {
"addressType": "Main Office",
"addressLine1": "123 Main Street",
"location": {
"city": "Brooklyn", "stateProvinceName": "New York"
},
"postalCode": "11229", "countryRegionName": "United States"
},
"id": "34e9873a-94c8-4720-9146-d63fb7840fad",
"_rid": "Ic8LAMEUVgACAAAAAAAAAA==",
"_ts": 1449812756,
"_self": "dbs/Ic8LAA==/colls/Ic8LAMEUVgA=/docs/Ic8LAMEUVgACAAAAAAAAAA==/",
"_etag": "\"00001000-0000-0000-0000-566a63140000\"",
"_attachments": "attachments/"
}
Created document 34e9873a-94c8-4720-9146-d63fb7840fad from dynamic object
如您所见,我们没有提供 Id,但是 DocumentDB 为我们生成了新文档的 Id。
As you can see, we haven’t supplied an Id, however DocumentDB generated this one for us for the new document.