Developing Stored Procedures in CosmosDB with .NET
Syntax
function sproc(params) {
// code
}
Example
function getUser(userId) {
var collection = getContext().getCollection();
var response = getContext().getResponse();
var query = "SELECT * FROM Users u WHERE u.id = '" + userId + "'";
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
query,
function (err, documents) {
if (err) {
throw new Error("Error: " + err.message);
}
if (!documents || !documents.length) {
response.setBody("No user found.");
} else {
response.setBody(JSON.stringify(documents[0]));
}
}
);
}
Output
The stored procedure will return the details of the user with the specified userId.
Explanation
Stored procedures are programs that are executed on the server side rather than the client side. They are used to perform complex operations on data stored in the database. In CosmosDB, stored procedures are written using JavaScript and can be executed from various client applications.
The above example shows a simple stored procedure that retrieves the details of a user with the specified userId from the Users collection in CosmosDB.
The stored procedure first gets a reference to the collection using the getContext() method. It then constructs a query to retrieve the user with the specified userId. The query is executed using the queryDocuments() method of the collection object. The callback function passed to this method is called when the query completes. If the query is successful and returns a document, the stored procedure returns the details of the user as a JSON string.
Use
Stored procedures can be used to perform complex operations on data stored in the database. They can be used for tasks such as aggregating data, validating data, and updating multiple documents in a transaction.
Important Points
- Stored procedures are executed on the server side.
- Stored procedures are written in JavaScript.
- Stored procedures can be executed from various client applications.
Summary
Stored procedures in CosmosDB provide a powerful way to perform complex operations on data stored in the database. They are written in JavaScript and can be executed on the server side from various client applications. Stored procedures can be used for tasks such as aggregating data, validating data, and updating multiple documents in a transaction.