Search code examples
azureazure-cosmosdbazure-cosmosdb-sqlapi

Azure Cosmos DB - count nested keys in subdocument


Having a Cosmos DB document with below schema:

{
  id: 1,
  nested: {
    key1: true,
    key2: false
  }
}

Is there any SQL operator I could use to count the keys in the "nested" subdocument? Similar to Object.keys(nested).length in JavaScript


Solution

  • You can write Cosmos Db UDF to get count of nested keys document.

    I have tried using sample data posted in question.

    UDF Code

    function getLength(nested) {
    return  Object.keys(nested).length;
    }
    

    Query to consume UDF

    SELECT udf.getLength(c.nested) AS LengthOfKeys FROM c
    

    Here is result of the above query.

    Sample data

    {
    "id": "1",
    "nested": {
    "key1": true,
    "key2": false
    }
    {
    "id": "2",
    "nested": {
    "key1": true,
    "key2": false,
    "key3": "hello"
    }