0
0
AzureHow-ToBeginner · 4 min read

How to Query Cosmos DB: Simple Guide with Examples

To query Cosmos DB, use the SQL API with SELECT statements inside your application or Azure portal. Queries filter and retrieve data from containers using JSON-based syntax similar to SQL.
📐

Syntax

The basic query syntax in Cosmos DB uses SQL-like commands. You start with SELECT to choose fields, FROM to specify the container, and optional WHERE to filter results.

  • SELECT: Fields to retrieve, e.g., * for all.
  • FROM: The container or collection name.
  • WHERE: Conditions to filter data.
sql
SELECT * FROM c WHERE c.id = '12345'
💻

Example

This example shows how to query Cosmos DB using the Azure Cosmos DB SDK for JavaScript. It retrieves all items where the category is books.

javascript
import { CosmosClient } from "@azure/cosmos";

const endpoint = "https://your-account.documents.azure.com:443/";
const key = "your-primary-key";
const client = new CosmosClient({ endpoint, key });

async function queryItems() {
  const database = client.database("LibraryDB");
  const container = database.container("Items");

  const querySpec = {
    query: "SELECT * FROM c WHERE c.category = @category",
    parameters: [
      { name: "@category", value: "books" }
    ]
  };

  const { resources: items } = await container.items.query(querySpec).fetchAll();
  console.log(items);
}

queryItems();
Output
[ { "id": "1", "title": "Learn Cosmos DB", "category": "books" }, { "id": "2", "title": "Azure Guide", "category": "books" } ]
⚠️

Common Pitfalls

Common mistakes when querying Cosmos DB include:

  • Not using parameterized queries, which can cause errors or security risks.
  • Forgetting to specify the correct container or database.
  • Using unsupported SQL features like JOINs on unrelated containers.
  • Ignoring case sensitivity in property names.

Always use parameters to avoid injection and check container names carefully.

javascript
/* Wrong: Direct string interpolation (unsafe) */
const query = `SELECT * FROM c WHERE c.name = '${userInput}'`;

/* Right: Use parameters to safely pass values */
const querySpec = {
  query: "SELECT * FROM c WHERE c.name = @name",
  parameters: [{ name: "@name", value: userInput }]
};
📊

Quick Reference

Here is a quick cheat sheet for Cosmos DB queries:

ClauseDescriptionExample
SELECTChoose fields to returnSELECT c.id, c.name FROM c
FROMSpecify container aliasFROM c
WHEREFilter resultsWHERE c.age > 30
ORDER BYSort resultsORDER BY c.name ASC
OFFSET LIMITPaginate resultsOFFSET 5 LIMIT 10

Key Takeaways

Use SQL-like syntax with SELECT, FROM, and WHERE to query Cosmos DB.
Always use parameterized queries to avoid injection and errors.
Specify the correct database and container before querying.
Cosmos DB queries are case sensitive for property names.
Use SDKs like Azure Cosmos DB SDK for easy querying in code.