cosmos-db
  1. cosmos-db-querying-documents

Querying Documents in CosmosDB with .NET

Syntax

IQueryable<T> queryable =
    client.CreateDocumentQuery<T>(collectionLink, feedOptions)
        .Where(predicate)
        .OrderBy(orderBy)
        .Skip(skip)
        .Take(take)

Example

// Query documents by name and city
IQueryable<Customer> queryable = client.CreateDocumentQuery<Customer>(collectionLink)
    .Where(c => c.Name == "John" && c.City == "Seattle")
    .OrderBy(c => c.Age)
    .Skip(5)
    .Take(10);

IEnumerable<Customer> results = await queryable.ToListAsync();

Output

The results variable will contain an enumeration of Customer objects that match the query criteria.

Explanation

CosmosDB provides a SQL-like syntax for querying documents in a collection. The CreateDocumentQuery method returns an IQueryable<T> object that represents the query. You can chain multiple methods to filter, order, skip, and take the results.

Use

You can use CosmosDB document queries in your .NET applications to retrieve data from collections. You can specify the query criteria using the Where method, and you can order the results using the OrderBy method. You can also skip a certain number of results using the Skip method, and take a certain number of results using the Take method.

Important Points

  • You can use the DocumentClient class to create document queries in .NET applications.
  • You can specify the collection link and feed options when creating the queryable object.
  • You can chain multiple methods to filter, order, skip, and take the results.
  • You can use LINQ expressions to specify the query criteria.
  • You should use indexing to improve query performance.

Summary

In this tutorial, you learned how to use CosmosDB document queries in .NET applications. You learned how to specify query criteria using the Where method, and order the results using the OrderBy method. You also learned how to skip and take a certain number of results using the Skip and Take methods.

Published on: