Azure Cosmos DB 中的項目代表儲存在容器中的特定實體。 在 NoSQL API 中,項目是由具有唯一識別碼的 JSON 格式資料所組成。
建立項目的唯一識別碼
唯一識別碼是一個獨特的字串,用來識別容器內的物品。 建立新 JSON 文件時,該 id 屬性是唯一必要的屬性。 例如,這份 JSON 文件在 Azure Cosmos 資料庫中是有效項目:
{
"id": "unique-string-2309509"
}
在容器的範圍內,兩個項目不能共享相同的唯一識別碼。
這很重要
該 id 屬性區分大小寫。 名為 ID、 Id、 iD和 _id 的屬性將被視為任意的 JSON 屬性。
一旦建立,項目的 URI 格式如下:
https://<cosmos-account-name>.documents.azure.com/dbs/<database-name>/docs/<item-resource-identifier>
使用 URI 參照項目時,請使用系統產生的 資源識別碼 而非欄位 id 。 欲了解更多關於 Azure Cosmos DB for NoSQL 中系統產生項目屬性的資訊,請參見 項目屬性
建立項目
備註
本文中的範例假設您已經定義 C# 類型來代表名為 Product 的資料:
// C# record type for items in the container
public record Product(
string id,
string category,
string name,
int quantity,
bool sale
);
範例也假設你已經建立了一個名為 newItem 的 Product 類型的新物件:
// Create new item and add to container
Product item = new(
id: "68719518388",
category: "gear-surf-surfboards",
name: "Sunnox Surfboard",
quantity: 8,
sale: true
);
要建立項目,請呼叫以下其中一種方法:
非同步建立項目
以下範例非同步建立新項目:
Product createdItem = await container.CreateItemAsync<Product>(
item: item,
partitionKey: new PartitionKey("gear-surf-surfboards")
);
如果與現有項目的唯一識別碼有衝突,該 Container.CreateItemAsync<> 方法會拋出例外。 欲了解更多潛在例外情況,請參閱CreateItemAsync<>例外。
非同步替換項目
以下範例非同步替換現有項目:
Product replacedItem = await container.ReplaceItemAsync<Product>(
item: item,
id: "68719518388",
partitionKey: new PartitionKey("gear-surf-surfboards")
);
此 Container.ReplaceItemAsync<> 方法要求所提供的參數字串 id 與該參數的唯一識別碼 item 相符。
非同步地建立或取代項目
以下範例將建立新項目,或替換已存在且唯一識別碼相同的項目:
Product upsertedItem = await container.UpsertItemAsync<Product>(
item: item,
partitionKey: new PartitionKey("gear-surf-surfboards")
);
該 Container.UpsertItemAsync<> 方法會使用參數的唯一識別碼 item 來判斷是否與現有項目衝突,並適當替換該項目。
後續步驟
既然您已建立各種項目,請使用下一個指南來讀取項目。