Azure

Create an Item in Azure Cosmos DB

Last updated: October 26, 2023

This tutorial guides you through the process of creating a new item within an Azure Cosmos DB container. Items are the fundamental data units in Cosmos DB, analogous to documents in a document database or rows in a relational database.

Prerequisites

Methods to Create an Item

You can create items in Azure Cosmos DB using several methods, including the Azure portal, Azure SDKs, or REST API. This tutorial focuses on using the Azure SDK for Node.js as an example.

Using Azure SDK for Node.js

Ensure you have the Azure Cosmos DB SDK for Node.js installed:

npm install @azure/cosmos

Step 1: Import the CosmosClient Class

Begin by importing the necessary class from the SDK.

const { CosmosClient } = require("@azure/cosmos");

Step 2: Initialize the CosmosClient

You'll need your Cosmos DB endpoint and primary key to initialize the client. You can find these in the Azure portal under your Cosmos DB account's "Keys" section.

// Replace with your actual endpoint and key const endpoint = "YOUR_COSMOS_DB_ENDPOINT"; const key = "YOUR_COSMOS_DB_PRIMARY_KEY"; const databaseId = "YOUR_DATABASE_ID"; const containerId = "YOUR_CONTAINER_ID"; const client = new CosmosClient({ endpoint, key }); const database = client.database(databaseId); const container = database.container(containerId);

Step 3: Define the Item to Create

Create a JavaScript object representing the data you want to store as an item. Ensure it includes an `id` property, which is mandatory for each item.

const newItem = { id: "myUniqueItemId123", // Must be unique within the container category: "books", author: "Jane Doe", title: "The Azure Adventure", isbn: "978-3-16-148410-0", tags: ["azure", "cosmosdb", "tutorial"] };
Note: The `id` field must be a unique string (or number that can be converted to a string) within the container.

Step 4: Create the Item

Use the `items.create()` method of the container object to insert the new item.

async function createItem() { try { const { item } = await container.items.create(newItem); console.log(`Item created with ID: ${item.id}`); console.log("Created item:", item); } catch (error) { console.error("Error creating item:", error.message); } } createItem();

Example Output

Upon successful execution, you will see output similar to this in your console:

Item created with ID: myUniqueItemId123 Created item: { id: 'myUniqueItemId123', category: 'books', author: 'Jane Doe', title: 'The Azure Adventure', isbn: '978-3-16-148410-0', tags: [ 'azure', 'cosmosdb', 'tutorial' ], _rid: 'some_rid_value', _self: 'dbs/some_db_id/colls/some_coll_id/docs/myUniqueItemId123', _etag: 'some_etag_value', _attachments: 'attachments/', _ts: 1678886400 }

Azure Portal Method

You can also create an item directly through the Azure portal:

  1. Navigate to your Azure Cosmos DB account in the Azure portal.
  2. Select your database and then your container.
  3. Click on "Items" in the left-hand menu.
  4. Click the "+ New Item" button.
  5. Enter your item's JSON data in the editor. Make sure to include the `id` field.
  6. Click "Save".
Tip: When using the portal, the `id` field is automatically populated with a generated UUID if you don't provide one, but it's good practice to define it yourself for clarity and control.

Conclusion

You have now learned how to create an item in Azure Cosmos DB using both programmatic (Node.js SDK) and manual (Azure portal) methods. Items are the building blocks of your data in Cosmos DB, and mastering their creation is fundamental to using the service effectively.

Continue exploring the Azure Cosmos DB tutorials to learn more about querying, updating, and deleting items.