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.
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.
Ensure you have the Azure Cosmos DB SDK for Node.js installed:
npm install @azure/cosmosBegin by importing the necessary class from the SDK.
const { CosmosClient } = require("@azure/cosmos");
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);
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"]
};
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();
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
}
You can also create an item directly through the Azure portal:
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.