Overview of User Defined Functions

Learn how user-defined functions (UDFs) unlock more query possibilities in Cosmos DB.

Introduction

We might find that system functions are not enough in complex queries for our needs. Cosmos DB lets us define custom functions stored on the server side.

We can write them in JavaScript, and they work as expected. They take some inputs and return a value. For example, we can define a function that, given an input string, returns if it’s a palindrome.

Press + to interact
// ID = IS_PALINDROME
function isPalindrome(input) {
const len = input.length;
for (let i = 0; i < len / 2; i++) {
if (input[i] !== input[len - 1 - i])
return false;
}
return true;
}

Usage

The first way to use a UDF is in the WHERE clause. Imagine we have a container with two users, Alice and Bob. We can query which one has a palindrome name. ...