Welcome to our guide on Azure Cosmos DB! This tutorial will help you understand the basics of this powerful NoSQL database service, while also diving into advanced concepts. Whether you're a beginner or an intermediate developer, this guide has something for everyone.
Azure Cosmos DB is a globally distributed, multi-model database service provided by Microsoft as part of the Azure cloud platform. It allows you to store and manage structured and unstructured data using APIs for MongoDB, SQL, Cassandra, Gremlin, and Table.
Here's an example of inserting, querying, and deleting data using the MongoDB API:
// Import the Azure Cosmos DB SDK
const { MongoClient } = require("@azure/cosmosdb");
// Initialize the MongoDB client
const client = new MongoClient("mongodb://<your_account_name>.documents.azure.com:<your_port>/", {
auth: {
user: "<your_account_name>",
password: "<your_account_key>",
},
});
// Connect to the database and collection
const db = client.db("<your_database_name>");
const collection = db.collection("<your_container_name>");
// Insert a document
const document = { name: "John Doe", age: 30 };
await collection.insertOne(document);
// Query the collection
const cursor = collection.find({ age: 30 });
const result = await cursor.toArray();
console.log(result);
// Delete a document
await collection.deleteOne({ name: "John Doe" });Using the SQL API involves slightly different syntax:
// Import the Azure Cosmos DB SQL API SDK
const { CosmosClient } = require("@azure/cosmos");
// Initialize the Cosmos Client
const client = new CosmosClient("mongodb://<your_account_name>.documents.azure.com:<your_port>/", {
auth: {
user: "<your_account_name>",
password: "<your_account_key>",
},
});
// Create a new database and container
const databaseName = "<your_database_name>";
const containerName = "<your_container_name>";
const database = client.database(databaseName);
const container = database.container(containerName);
// Insert a document
await container.items.create({ id: 1, name: "Jane Smith", age: 28 });
// Query the container
const query = `SELECT * FROM c WHERE c.age = 28`;
const result = await container.items.query(query).fetchAll();
console.log(result);
// Delete a document
await container.item(`1`).delete();Which APIs does Azure Cosmos DB support?
Now that you've learned the basics of Azure Cosmos DB, you're ready to start exploring this powerful NoSQL database service. With its global distribution, multi-model capabilities, and ease of use, Azure Cosmos DB is an excellent choice for your next project.
Stay tuned for more tutorials on CodeYourCraft, where we'll dive deeper into Azure Cosmos DB and other exciting topics! 🎯
Happy coding! 💡