Connect to Azure Cosmos DB for NoSQL by using the SDK and run queries (AI-200 Exam Prep)

This post is a part of the AI-200: Developing AI Cloud Solutions on Azure  Exam Prep Hub.
This topic falls under these sections:
Develop AI solutions by using Azure data management services (25–30%)
   --> Develop AI solutions by using Azure Cosmos DB for NoSQL
      --> Connect to Azure Cosmos DB for NoSQL by using the SDK and run queries


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Overview

Azure Cosmos DB for NoSQL is a globally distributed, fully managed NoSQL database service designed for applications that require flexible schemas, low-latency access, and elastic scalability.

For the AI-200 exam, developers should understand how to:

  • Connect applications to Azure Cosmos DB for NoSQL.
  • Use the Azure Cosmos DB SDK.
  • Authenticate securely.
  • Create and access databases and containers.
  • Define partition keys.
  • Insert, read, update, and delete items.
  • Construct SQL queries for Cosmos DB.
  • Execute queries through the SDK.
  • Work with query parameters.
  • Understand partition-aware querying.
  • Process query results efficiently.
  • Recognize common performance considerations.

The key concept is that Azure Cosmos DB for NoSQL exposes a SQL-like query language, while the SDK provides the programming interface through which an application connects to the service and executes those queries.


1. Understanding the Azure Cosmos DB for NoSQL Data Model

Before connecting with an SDK, it is important to understand the hierarchy used by Azure Cosmos DB.

The basic structure is:

Cosmos DB account → Database → Container → Item

Cosmos DB account

The account is the top-level Azure resource. It provides the endpoint through which applications communicate with Cosmos DB.

An account contains one or more databases.

Database

A database provides a logical grouping of containers.

For example:

AI200CosmosAccount
└── CustomerDatabase

Container

A container is where items are stored.

A container is roughly analogous to a table in a relational database, although it is much more flexible because Cosmos DB items can have different structures.

CustomerDatabase
├── Customers
├── Orders
└── Products

A container also defines the partition key path, which is extremely important for scalability and query performance.

Item

An item is a JSON document.

For example:

{
"id": "customer-1001",
"customerName": "John Smith",
"country": "US",
"email": "john@example.com",
"loyaltyLevel": "Gold"
}

Unlike a relational table, another item in the same container could contain additional properties.


2. Connecting to Azure Cosmos DB

An application needs two primary pieces of information to connect to a Cosmos DB account:

  1. The Cosmos DB account endpoint.
  2. A supported authentication mechanism.

A typical endpoint looks conceptually like:

https://<account-name>.documents.azure.com:443/

The SDK uses this endpoint to communicate with the Cosmos DB service.


3. Authentication

Authentication is an important exam topic because applications should avoid embedding long-lived credentials directly in source code.

Several authentication approaches are available, including:

  • Microsoft Entra ID-based authentication.
  • Managed identities.
  • Account keys.
  • Connection strings.

For production Azure applications, Microsoft Entra ID with managed identity is generally preferable when supported by the application’s architecture because credentials do not need to be stored in application configuration or source code.

For example, an application running on an Azure service can use its managed identity to authenticate to Cosmos DB.

The conceptual flow is:

Application
│ Managed identity
Microsoft Entra ID
│ Token
Azure Cosmos DB

Exam point

If a question asks for the most secure way for an Azure-hosted application to authenticate to Cosmos DB without storing credentials, look for an answer involving:

Microsoft Entra ID + managed identity + appropriate Cosmos DB data-plane permissions.


4. Using the Azure Cosmos DB SDK

Microsoft provides SDKs for several programming languages, including:

  • .NET
  • Java
  • JavaScript/TypeScript
  • Python

The SDK provides classes and methods for interacting with Cosmos DB.

For example, a .NET application can use the Azure Cosmos DB SDK package.

A simplified connection looks like:

var client = new CosmosClient(
endpoint,
credential);

The CosmosClient represents the client connection to the Cosmos DB account.

Applications can then access databases and containers through the client.

Conceptually:

CosmosClient
└── Database
└── Container
├── Create item
├── Read item
├── Replace item
├── Delete item
└── Query items

5. Reuse the CosmosClient

A common application-design mistake is creating a new CosmosClient for every database operation.

Instead, applications should generally create and reuse a single CosmosClient instance for the lifetime of the application.

For example:

private static CosmosClient client = new CosmosClient(
endpoint,
credential);

The SDK manages connections internally.

Creating clients repeatedly can cause unnecessary connection overhead and negatively affect performance.

Exam tip

If a question presents code that creates a new CosmosClient for every request, consider whether the question is testing your knowledge of client reuse.

Reuse the client rather than repeatedly creating new instances.


6. Accessing a Database

Once the client has been created, the application can obtain a reference to a database.

For example:

Database database = client.GetDatabase("CustomerDatabase");

This does not necessarily mean that the database has been created.

It obtains a client-side reference to the database.

If the database needs to be created, the SDK provides methods such as:

DatabaseResponse response =
await client.CreateDatabaseIfNotExistsAsync("CustomerDatabase");

The CreateIfNotExists pattern is useful when an application should create the resource only when necessary.


7. Accessing a Container

After obtaining a database reference, the application can access a container:

Container container =
database.GetContainer("Customers");

As with GetDatabase(), obtaining a container reference does not mean that the container has been created.

A container can be created when necessary:

ContainerResponse response =
await database.CreateContainerIfNotExistsAsync(
"Customers",
"/country");

The second parameter specifies the partition key path.

In this example:

/country

is the partition key path.


8. Partition Keys

Partitioning is fundamental to Cosmos DB.

A container distributes its items across physical partitions based on the configured partition key.

For example:

{
"id": "customer-1001",
"country": "US",
"name": "John Smith"
}

If /country is the partition key path, the value:

US

determines the logical partition to which the item belongs.

A good partition key should generally provide:

  • High cardinality.
  • Even distribution.
  • Sufficient request-volume distribution.
  • Values that match common access patterns.

Why this matters for queries

If a query includes the partition key value, Cosmos DB can often limit the query to the relevant partition rather than querying every partition.

This is called a single-partition query or targeted query, depending on the scenario.

A query that does not provide a partition key value may require a cross-partition query.


9. Creating Items

Items are JSON documents.

A .NET application can create an item using the SDK:

var customer = new
{
id = "customer-1001",
country = "US",
name = "John Smith",
loyaltyLevel = "Gold"
};
ItemResponse<dynamic> response =
await container.CreateItemAsync(
customer,
new PartitionKey("US"));

The partition key value supplied to the SDK should correspond to the item’s partition key.

For a container partitioned on:

/country

the request should specify:

new PartitionKey("US")

10. Reading an Item

When the application’s partition key and item ID are known, the SDK can directly retrieve an item.

For example:

ItemResponse<Customer> response =
await container.ReadItemAsync<Customer>(
"customer-1001",
new PartitionKey("US"));

This is generally much more efficient than querying for the item because Cosmos DB can directly address the item using its ID and partition key.

Important distinction

Consider these two operations:

ReadItem(id, partitionKey)

versus:

SELECT * FROM c WHERE c.id = "customer-1001"

The point read supplies both the item ID and partition key and is the preferred operation when those values are known.

Exam tip

If a question asks how to retrieve one known item as efficiently as possible, look for:

Point read using the item’s ID and partition key.


11. Updating Items

The SDK supports updating existing items.

Depending on the required behavior, developers can use operations such as:

  • Replace
  • Upsert
  • Patch

Replace

Replace generally replaces the entire item.

Upsert

Upsert means:

Update the item if it exists; otherwise create it.

For example:

await container.UpsertItemAsync(
customer,
new PartitionKey("US"));

Patch

Patch modifies selected properties without requiring the application to replace the entire document.

For example, an application might update only:

loyaltyLevel

rather than sending the entire customer document.

This can reduce the amount of data transmitted and simplify partial updates.


12. Deleting Items

An item can be deleted using its ID and partition key:

await container.DeleteItemAsync<Customer>(
"customer-1001",
new PartitionKey("US"));

Again, knowing both the ID and partition key allows Cosmos DB to directly identify the item.


13. Querying Azure Cosmos DB for NoSQL

Cosmos DB for NoSQL uses a SQL-like query language.

A simple query is:

SELECT * FROM c

The c represents each item being queried.

For example:

SELECT *
FROM c
WHERE c.country = "US"

This returns items whose country property is US.


14. Selecting Specific Properties

Applications don’t always need the entire document.

Instead of:

SELECT *
FROM c

you can select specific properties:

SELECT
c.id,
c.name,
c.email
FROM c

This can reduce the amount of data returned to the application.

It can also make the application’s intent clearer.


15. Filtering Results

The WHERE clause filters documents.

For example:

SELECT *
FROM c
WHERE c.loyaltyLevel = "Gold"

Multiple conditions can be combined:

SELECT *
FROM c
WHERE c.country = "US"
AND c.loyaltyLevel = "Gold"

Other operators include:

=
!=
<
>
<=
>=
AND
OR

16. Parameterized Queries

Applications should avoid constructing queries by concatenating user input into SQL strings.

For example, this pattern should be avoided:

string query =
"SELECT * FROM c WHERE c.name = '" + userName + "'";

Instead, use parameterized queries.

For example:

var query = new QueryDefinition(
"SELECT * FROM c WHERE c.name = @name")
.WithParameter("@name", userName);

This approach:

  • Separates query structure from values.
  • Helps prevent injection-style problems.
  • Makes query reuse easier.
  • Provides cleaner application code.

17. Executing a Query

The SDK provides query APIs that allow the application to execute a QueryDefinition.

For example:

var query = new QueryDefinition(
"SELECT * FROM c WHERE c.country = @country")
.WithParameter("@country", "US");
using FeedIterator<Customer> iterator =
container.GetItemQueryIterator<Customer>(query);
while (iterator.HasMoreResults)
{
FeedResponse<Customer> response =
await iterator.ReadNextAsync();
foreach (Customer customer in response)
{
Console.WriteLine(customer.name);
}
}

This demonstrates an important concept:

Cosmos DB queries can return results in multiple pages.


18. FeedIterator and Pagination

A query may return more data than can reasonably be delivered in one response.

The SDK therefore exposes query results through an iterator.

Conceptually:

Query
Page 1
Page 2
Page 3
...

The application checks:

iterator.HasMoreResults

and retrieves each page using:

await iterator.ReadNextAsync()

This is important for scalability.

Exam tip

If a question asks how to process a potentially large Cosmos DB query result set, look for an answer involving:

FeedIterator / paginated results rather than loading the entire result set into memory.


19. Cross-Partition Queries

Suppose a container uses:

/country

as its partition key.

A query such as:

SELECT *
FROM c
WHERE c.country = "US"

provides a partition key value.

This allows Cosmos DB to target the appropriate partition.

However, a query such as:

SELECT *
FROM c
WHERE c.loyaltyLevel = "Gold"

does not specify the partition key.

The service may therefore need to query multiple partitions.

This is a cross-partition query.

Cross-partition queries are not inherently wrong. They are sometimes necessary.

However, they can require more resources and incur higher request charges than targeted queries.


20. Supplying a Partition Key to a Query

The SDK can provide the partition key value separately from the query itself.

For example:

var query = new QueryDefinition(
"SELECT * FROM c WHERE c.loyaltyLevel = @level")
.WithParameter("@level", "Gold");
var requestOptions = new QueryRequestOptions
{
PartitionKey = new PartitionKey("US")
};
using FeedIterator<Customer> iterator =
container.GetItemQueryIterator<Customer>(
query,
requestOptions: requestOptions);

The application is effectively telling Cosmos DB:

Search only the US partition.

This can significantly improve query efficiency when the access pattern permits it.


21. Query Performance and Request Units

Azure Cosmos DB measures database operations using Request Units (RUs).

The RU charge depends on factors such as:

  • The operation being performed.
  • The amount of data processed.
  • The complexity of the query.
  • Indexing.
  • Number of partitions involved.
  • Number of documents examined.
  • Amount of data returned.

A query that scans many partitions can consume substantially more RUs than a targeted query.

Applications should therefore design queries and partition keys together.


22. Indexing

Cosmos DB automatically indexes properties by default in many common configurations.

Indexes help Cosmos DB efficiently locate matching documents.

However, indexing every property isn’t always optimal for every workload.

Applications with specialized workloads may need to configure indexing policies to balance:

  • Query performance.
  • Write performance.
  • Storage.
  • RU consumption.

For the AI-200 exam, understand the relationship:

More/appropriate indexing
Efficient queries
Potentially lower query cost

But indexing isn’t a substitute for good partition-key design.


23. Querying Arrays and Nested Properties

Cosmos DB documents can contain nested objects and arrays.

For example:

{
"id": "1001",
"customer": {
"name": "John",
"country": "US"
},
"orders": [
{
"id": "O100",
"total": 125
},
{
"id": "O101",
"total": 200
}
]
}

A nested property can be accessed using dot notation:

SELECT c.customer.name
FROM c

Cosmos DB also supports array operations.

For example, the ARRAY_CONTAINS function can determine whether an array contains a particular value.

The ability to query nested JSON is one of the significant advantages of the NoSQL model.


24. Query Functions

Azure Cosmos DB for NoSQL supports many built-in functions.

Examples include functions for:

  • Strings.
  • Arrays.
  • Mathematical calculations.
  • Date/time operations.
  • Type checking.
  • Spatial data.

For example:

SELECT *
FROM c
WHERE CONTAINS(c.name, "Smith")

Another example:

SELECT *
FROM c
WHERE ARRAY_CONTAINS(c.tags, "AI")

The important exam concept is not memorizing every function but understanding that Cosmos DB’s query language provides rich querying capabilities against JSON documents.


25. Querying With ORDER BY

Results can be sorted using ORDER BY.

For example:

SELECT
c.id,
c.name,
c.total
FROM c
ORDER BY c.total DESC

This returns the highest totals first.

Queries can also use OFFSET and LIMIT patterns for controlled result sets.


26. Querying With Aggregates

Cosmos DB supports aggregate functions such as:

COUNT
SUM
AVG
MIN
MAX

For example:

SELECT VALUE COUNT(1)
FROM c
WHERE c.country = "US"

The VALUE keyword is useful when the desired result is the scalar value rather than an object containing a property.


27. Querying With SELECT VALUE

Consider:

SELECT c.name
FROM c

This returns objects such as:

{
"name": "John"
}

Using:

SELECT VALUE c.name
FROM c

returns the values directly:

"John"
"Mary"
"Robert"

This distinction can appear in exam questions.


28. Querying With Continuation Tokens

Cosmos DB can return a continuation token when a query result spans multiple pages.

The application can use the continuation token to continue retrieving results.

This is particularly useful for:

  • Large result sets.
  • Pagination.
  • Resuming queries.
  • Avoiding the need to retrieve everything at once.

The SDK’s iterator abstraction commonly handles this pagination process for the application.


29. Point Reads vs. Queries

One of the most important distinctions to understand is:

RequirementPreferred operation
Retrieve a known item by ID and partition keyPoint read
Find items matching conditionsQuery
Retrieve multiple items from a partitionQuery
Modify one known itemReplace/Patch
Create or update an itemUpsert
Remove one known itemDelete

Example

If you know:

id = customer-1001
country = US

use:

ReadItem(id, partitionKey)

rather than:

SELECT * FROM c WHERE c.id = "customer-1001"

The point read is designed specifically for this scenario.


30. Common Exam Traps

Trap 1: Confusing the database with the container

A database contains containers.

A container contains items.


Trap 2: Treating Cosmos DB like a relational database

Cosmos DB for NoSQL stores JSON documents and uses containers rather than relational tables.


Trap 3: Forgetting the partition key

The partition key is central to Cosmos DB scalability and query performance.


Trap 4: Using a query for a known item

If both the item ID and partition key are known, use a point read.


Trap 5: Creating a CosmosClient for every request

The client should generally be reused.


Trap 6: Building queries with string concatenation

Use parameterized queries with QueryDefinition.


Trap 7: Assuming every query is single-partition

A query that doesn’t target a partition may become a cross-partition query.


Trap 8: Loading all results into memory

Use the SDK’s iterator/pagination model to process potentially large result sets incrementally.


31. AI-200 Exam Takeaways

For this topic, make sure you can explain the following without referring to documentation:

  1. Cosmos DB hierarchy
    • Account → Database → Container → Item.
  2. CosmosClient
    • Establishes the SDK connection to the Cosmos DB account.
    • Should generally be reused.
  3. Authentication
    • Understand account keys versus Microsoft Entra ID and managed identity.
  4. Partition keys
    • Determine logical data distribution.
    • Are critical to scalability and query performance.
  5. Point reads
    • Use item ID + partition key when both are known.
  6. Queries
    • Use Cosmos DB’s SQL-like query language.
  7. Parameterized queries
    • Use QueryDefinition and parameters rather than string concatenation.
  8. Cross-partition queries
    • Can occur when a query isn’t targeted to a specific partition.
  9. FeedIterator
    • Used to process paginated query results.
  10. Request Units
    • Measure Cosmos DB resource consumption.
  11. Indexing
    • Supports efficient queries and can affect RU consumption.
  12. CRUD operations
    • Create, read, update, upsert, patch, and delete items through the SDK.

Practice Exam Questions

Question 1

An application running in Azure needs to connect to Azure Cosmos DB for NoSQL. The organization requires that no database credentials be stored in application configuration.

Which authentication approach should the developer prefer?

A. Store the Cosmos DB account key in the application’s source code.

B. Store the Cosmos DB connection string in an environment variable.

C. Use a managed identity with Microsoft Entra ID authentication and appropriate Cosmos DB permissions.

D. Create a new Cosmos DB account key whenever the application starts.

Answer: C

Explanation:
A managed identity allows an Azure-hosted application to authenticate without storing long-lived credentials in application code or configuration. The identity must have the appropriate permissions to access Cosmos DB. Hard-coded keys and connection strings introduce credential-management risks.


Question 2

A container uses /customerId as its partition key. An application needs to retrieve a specific item, and it already knows both the item’s id and customerId.

Which operation should the application use?

A. A point read using the item ID and partition key.

B. A cross-partition SQL query.

C. A query using ORDER BY.

D. A query using GROUP BY.

Answer: A

Explanation:
When the item ID and partition key are known, a point read is the appropriate operation. It directly addresses the item instead of executing a query across documents.


Question 3

A developer needs to allow users to search for customers by name. The name is supplied by the user at runtime.

Which approach should the developer use?

A. Concatenate the user input into the SQL string.

B. Encode the user’s input as Base64 and concatenate it into the SQL string.

C. Create a separate container for each possible customer name.

D. Use a parameterized QueryDefinition.

Answer: D

Explanation:
A parameterized query separates query structure from user-supplied values. The Cosmos DB SDK supports parameters through QueryDefinition.WithParameter(). This is preferable to dynamically concatenating user input into query strings.


Question 4

A Cosmos DB container is partitioned by /region. An application executes:

SELECT *
FROM c
WHERE c.productCategory = "AI"

The query does not specify a region.

What should the developer understand about this query?

A. It automatically becomes a point read.

B. It may require a cross-partition query.

C. It can only return one document.

D. Cosmos DB automatically changes the partition key for the query.

Answer: B

Explanation:
Because the query does not restrict the /region partition key, Cosmos DB may need to query multiple partitions. Cross-partition queries are supported, but they can consume more resources than targeted queries.


Question 5

An application executes a query that can return hundreds of thousands of documents. The developer wants to avoid loading all results into memory simultaneously.

Which SDK approach is most appropriate?

A. Use a FeedIterator and process the results page by page.

B. Convert the query into a point read.

C. Increase the item’s partition key value.

D. Retrieve the entire result set using a single string response.

Answer: A

Explanation:
Cosmos DB queries can return results in multiple pages. The SDK’s FeedIterator allows an application to retrieve and process each page incrementally, which is more appropriate for large result sets.


Question 6

An application repeatedly creates a new CosmosClient object every time it performs a database operation.

What should the developer do?

A. Create a new client for every item.

B. Create two clients for every request to provide redundancy.

C. Reuse a CosmosClient instance for the lifetime of the application.

D. Replace the SDK with direct HTTP calls for every operation.

Answer: C

Explanation:
CosmosClient is designed to be reused. Creating clients repeatedly introduces unnecessary connection-management overhead and can negatively affect application performance.


Question 7

A container uses /country as its partition key. An application frequently retrieves customers when both their customer ID and country are known.

Which design provides the most direct access to an individual customer?

A. Store all customers in a single partition.

B. Use a point read with the customer ID and country as the partition key value.

C. Run a cross-partition query for every customer.

D. Use ORDER BY country before retrieving the customer.

Answer: B

Explanation:
A point read using the item ID and partition key can directly locate an item. This is preferable to running a query when the application’s access pattern already provides both values.


Question 8

A developer wants to update only the status property of a large Cosmos DB document rather than replacing the entire document.

Which operation is most appropriate?

A. CreateItem

B. ReadItem

C. DeleteItem

D. Patch

Answer: D

Explanation:
Patch is designed for modifying specific properties or paths within an existing item without requiring the entire document to be replaced.


Question 9

A Cosmos DB application performs a query that searches across many physical partitions. The query consumes significantly more Request Units than a similar query that targets a single partition.

What is the most likely explanation?

A. Cross-partition queries can require work across multiple partitions.

B. Cosmos DB charges a fixed number of RUs for every query regardless of its scope.

C. Point reads always consume more RUs than cross-partition queries.

D. Partition keys have no relationship to query performance.

Answer: A

Explanation:
Queries that span multiple partitions may require Cosmos DB to perform work across those partitions, which can increase resource consumption. Designing partition keys around application access patterns can help reduce unnecessary cross-partition queries.


Question 10

A developer wants a query to return only customer names as scalar values instead of objects such as:

{
"name": "John Smith"
}

Which query should the developer use?

A.

SELECT *
FROM c

B.

SELECT c
FROM c

C.

SELECT VALUE c.name
FROM c

D.

SELECT OBJECT(c.name)
FROM c

Answer: C

Explanation:
SELECT VALUE returns the selected expression directly rather than wrapping it in a JSON object. Therefore:

SELECT VALUE c.name
FROM c

returns scalar values such as:

"John Smith"
"Mary Jones"

rather than objects containing a name property.


Final Exam Reminder

For AI-200, don’t think of Cosmos DB simply as “a NoSQL database that I can query.” Think about the relationship between data modeling, partitioning, SDK operations, queries, and performance.

The most important decision pattern is:

Know the item ID + partition key? → Point read.
Need to find items based on criteria? → Query.
Know the partition key? → Target the partition when possible.
Large result set? → Process pages with the SDK iterator.
User-supplied values? → Parameterize the query.
Azure-hosted application without stored credentials? → Prefer managed identity/Entra ID where supported.


Go to the AI-200 Exam Prep Hub main page

Leave a comment