Query items in Azure Cosmos DB for NoSQL using JavaScript
APPLIES TO: NoSQL
Items in Azure Cosmos DB represent entities stored within a container. In the API for NoSQL, an item consists of JSON-formatted data with a unique identifier. When you issue queries using the API for NoSQL, results are returned as a JSON array of JSON documents.
Query items using SQL
The Azure Cosmos DB for NoSQL supports the use of Structured Query Language (SQL) to perform queries on items in containers. A simple SQL query like SELECT * FROM products
returns all items and properties from a container. Queries can be even more complex and include specific field projections, filters, and other common SQL clauses:
SELECT
p.name,
p.quantity
FROM
products p
WHERE
p.quantity > 500
To learn more about the SQL syntax for Azure Cosmos DB for NoSQL, see Getting started with SQL queries.
Query an item
Create an array of matched items from the container's items object using the query method.
const querySpec = {
query: `SELECT * FROM ${container.id} f WHERE f.name = @name`,
parameters: [{
name: "@name",
value: "Sunnox Surfboard",
}],
};
const { resources } = await container.items.query(querySpec).fetchAll();
for (const product of resources) {
console.log(`${product.name}, ${product.quantity} in stock `);
}
The query method returns a QueryIterator object. Use the iterator's fetchAll method to retrieve all the results. The QueryIterator also provides fetchNext, hasMoreResults, and other methods to help you use the results.
Next steps
Now that you've queried multiple items, try one of our end-to-end tutorials with the API for NoSQL.