Bird
Raised Fist0
Azurecloud~10 mins

Functions with Cosmos DB integration in Azure - Interactive Code Practice

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to bind the Azure Function to Cosmos DB input.

Azure
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, [CosmosDB(databaseName: "MyDb", collectionName: "MyCollection", ConnectionStringSetting = [1], Id = "1", PartitionKey = "partitionKey")] MyDocument doc, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");
    return new OkObjectResult(doc);
}
Drag options to blanks, or click blank then click option'
A"AzureWebJobsStorage"
B"CosmosDBConnection"
C"SqlConnection"
D"EventHubConnection"
Attempts:
3 left
💡 Hint
Common Mistakes
Using storage account connection string instead of Cosmos DB connection string.
Using incorrect or missing connection string setting name.
2fill in blank
medium

Complete the code to output a document to Cosmos DB from the Azure Function.

Azure
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, [CosmosDB(databaseName: "MyDb", collectionName: "MyCollection", ConnectionStringSetting = "CosmosDBConnection")] IAsyncCollector<MyDocument> documentsOut, ILogger log)
{
    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    var inputDoc = JsonConvert.DeserializeObject<MyDocument>(requestBody);
    await documentsOut.[1](inputDoc);
    return new OkResult();
}
Drag options to blanks, or click blank then click option'
AAddAsync
BAdd
CWriteAsync
DInsert
Attempts:
3 left
💡 Hint
Common Mistakes
Using synchronous Add method which does not exist.
Using incorrect method names like WriteAsync or Insert.
3fill in blank
hard

Fix the error in the Cosmos DB output binding attribute to specify the partition key.

Azure
[CosmosDB(databaseName: "MyDb", collectionName: "MyCollection", ConnectionStringSetting = "CosmosDBConnection", [1] = "partitionKey")] IAsyncCollector<MyDocument> documentsOut
Drag options to blanks, or click blank then click option'
APartitionKey
BPartitionKeyPath
CPartitionKeyValue
DPartitionKeySetting
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect property names like PartitionKeyPath or PartitionKeyValue.
Omitting the partition key when required.
4fill in blank
hard

Fill both blanks to correctly read multiple documents from Cosmos DB using a SQL query.

Azure
public static IEnumerable<MyDocument> Run([CosmosDB(databaseName: "MyDb", collectionName: "MyCollection", ConnectionStringSetting = "CosmosDBConnection", SqlQuery = [1])] IEnumerable<MyDocument> documents, ILogger log)
{
    log.LogInformation("Documents retrieved.");
    return documents.Where(doc => doc.[2] > 10);
}
Drag options to blanks, or click blank then click option'
A"SELECT * FROM c WHERE c.status = 'active'"
B"SELECT * FROM c"
Cscore
Dstatus
Attempts:
3 left
💡 Hint
Common Mistakes
Using a SQL query that filters documents already, then filtering again in code.
Using a string property like 'status' in a numeric comparison.
5fill in blank
hard

Fill all three blanks to correctly define a Cosmos DB trigger function that processes changed documents.

Azure
public static void Run([CosmosDBTrigger(databaseName: [1], collectionName: [2], ConnectionStringSetting: [3], LeaseCollectionName = "leases")] IReadOnlyList<MyDocument> input, ILogger log)
{
    foreach (var doc in input)
    {
        log.LogInformation($"Document id: {doc.id} processed.");
    }
}
Drag options to blanks, or click blank then click option'
A"MyDb"
B"MyCollection"
C"CosmosDBConnection"
D"leases"
Attempts:
3 left
💡 Hint
Common Mistakes
Using the lease collection name as the connection string setting.
Mixing up database and collection names.

Practice

(1/5)
1. What is the main benefit of using Azure Functions with Cosmos DB integration?
easy
A. Automatically run code when data changes in Cosmos DB
B. Manually trigger code only through HTTP requests
C. Store large files directly in Cosmos DB
D. Replace Cosmos DB with Azure Blob Storage

Solution

  1. Step 1: Understand Azure Functions with Cosmos DB

    Azure Functions can be triggered automatically by changes in Cosmos DB data.
  2. Step 2: Identify the main benefit

    This automatic trigger saves resources by running code only when needed, without manual calls.
  3. Final Answer:

    Automatically run code when data changes in Cosmos DB -> Option A
  4. Quick Check:

    Functions trigger on data changes = A [OK]
Hint: Functions run on data change events automatically [OK]
Common Mistakes:
  • Thinking functions run only on HTTP triggers
  • Confusing Cosmos DB with file storage
  • Assuming manual triggers are required
2. Which of the following is the correct binding direction for a Cosmos DB input binding in an Azure Function?
easy
A. direction: "out"
B. direction: "both"
C. direction: "trigger"
D. direction: "in"

Solution

  1. Step 1: Recall binding directions

    Input bindings receive data into the function, so their direction is "in".
  2. Step 2: Match binding direction for Cosmos DB input

    Cosmos DB input binding must have direction set to "in" to read data.
  3. Final Answer:

    direction: "in" -> Option D
  4. Quick Check:

    Input binding direction = in [OK]
Hint: Input bindings always use direction "in" [OK]
Common Mistakes:
  • Using "out" for input bindings
  • Confusing trigger with input binding
  • Using invalid directions like "both"
3. Given this Azure Function code snippet triggered by Cosmos DB changes, what will be logged if a new document with id "123" is added?
module.exports = async function (context, documents) {
  if (!!documents && documents.length > 0) {
    context.log(`Document id: ${documents[0].id}`);
  }
};
medium
A. No output logged
B. Document id: undefined
C. Document id: 123
D. Error: documents is not defined

Solution

  1. Step 1: Understand the trigger input

    The function receives an array 'documents' with changed documents; the first document has id "123".
  2. Step 2: Analyze the logging statement

    The code logs the id of the first document, which is "123".
  3. Final Answer:

    Document id: 123 -> Option C
  4. Quick Check:

    documents[0].id = 123 logged [OK]
Hint: documents array holds changed items; access first with documents[0] [OK]
Common Mistakes:
  • Assuming documents is undefined
  • Logging without checking documents length
  • Confusing document id property
4. You wrote an Azure Function triggered by Cosmos DB changes, but it never runs when documents change. Which is the most likely cause?
medium
A. The function code has a syntax error
B. The function.json binding has incorrect connection string name
C. The Cosmos DB container is empty
D. The function app is stopped

Solution

  1. Step 1: Check trigger configuration

    If the connection string name in function.json is wrong, the function won't connect to Cosmos DB changes.
  2. Step 2: Consider other causes

    Syntax errors cause failures but usually show errors; empty container still triggers on inserts; stopped app won't run but question implies function exists.
  3. Final Answer:

    The function.json binding has incorrect connection string name -> Option B
  4. Quick Check:

    Wrong connection string stops trigger [OK]
Hint: Check connection string name in function.json first [OK]
Common Mistakes:
  • Ignoring binding configuration errors
  • Assuming empty container prevents triggers
  • Not verifying function app status
5. You want to create an Azure Function that writes a summary document to Cosmos DB whenever multiple documents are added. Which binding setup should you use?
hard
A. Use Cosmos DB trigger for input and Cosmos DB output binding for summary document
B. Use HTTP trigger and Cosmos DB input binding only
C. Use Cosmos DB input binding only, no trigger
D. Use Timer trigger and Cosmos DB output binding only

Solution

  1. Step 1: Identify trigger for reacting to data changes

    Cosmos DB trigger runs the function automatically when documents change.
  2. Step 2: Use output binding to write summary

    Output binding lets the function write a new summary document back to Cosmos DB.
  3. Final Answer:

    Use Cosmos DB trigger for input and Cosmos DB output binding for summary document -> Option A
  4. Quick Check:

    Trigger input + output binding for writing = C [OK]
Hint: Trigger on changes, output binding to write summary [OK]
Common Mistakes:
  • Using HTTP trigger instead of Cosmos DB trigger
  • Missing output binding for writing data
  • Using timer trigger without data event