cosmos-db
  1. cosmos-db-connecting-to-cosmosdb

Connecting to CosmosDB with .NET

Syntax

DocumentClient client = new DocumentClient(new Uri(endpointUrl), primaryKey);

Example

using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using System;
using System.Linq;

namespace CosmosDbDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string endpointUrl = "https://<cosmosdb-account>.documents.azure.com:443/";
            string primaryKey = "<cosmosdb-primary-key>";
            DocumentClient client = new DocumentClient(new Uri(endpointUrl), primaryKey);

            var query = client.CreateDocumentQuery<dynamic>(
                UriFactory.CreateDocumentCollectionUri("<database-name>", "<collection-name>"),
                "SELECT * FROM c",
                new FeedOptions { MaxItemCount = -1 })
            .ToList();

            foreach (var item in query)
            {
                Console.WriteLine(item);
            }
        }
    }
}

Output

{
    "id": "abc123",
    "name": "John Doe",
    "age": 35
}
{
    "id": "def456",
    "name": "Jane Smith",
    "age": 28
}

Explanation

This code connects to a CosmosDB account using the primary key and retrieves all documents from a specified collection within a specified database. The query is executed using the SQL syntax familiar to users of relational databases.

Use

This code sample can be used as a starting point for any .NET application that needs to interact with a CosmosDB database.

Important Points

  • The DocumentClient class must be instantiated with the endpoint URL and primary key for the CosmosDB account.
  • The UriFactory.CreateDocumentCollectionUri method is used to construct the URI for a specific collection within a specific database.
  • The query is executed using the CreateDocumentQuery method, which returns a strongly-typed list of documents that match the query.
  • The FeedOptions class is used to specify options for the query, such as the maximum number of items to retrieve.

Summary

This code sample demonstrates how to connect to a CosmosDB account using the .NET DocumentClient class and retrieve documents from a collection using a SQL query. The code can be easily adapted to suit the needs of any .NET application that needs to interact with a CosmosDB database.

Published on: