First result in a returned list - CosmosDB query

Viewed 51

I am learning the CosmosDB SQL API for JS and am having what I believe is a basic issue in understanding Typescript. The function I'm calling returns a group of items, which are just JSON objects. In my query, however, I just want to replicate the SQL aggregate function to count total records. Long story short, how do I return just a single simple integer for the number of items returned by the query?

export class AssetTypeRepository extends BaseRepository<AssetType> {
    -- A SIMPLE FUNCTION TO RETURN THE NUMBER OF RECORDS IN A SET
     count(): Promise<number> {
        const { resources: items } = this._container.items
            .query("select count(1) as recordCount from c")
            .fetchAll()[0]; -- SHOULD I JUST GET INDEX 0 SINCE AN AGGREGATE WILL RETURN EXACTLY ONE ROW?
        
        return Promise.resolve(/* just a plain ol' integer goes here, right? */);
    }
}

Here's an example from some documentation, but it's returning items, not a scalar value.

const querySpec: SqlQuerySpec = {
  query: "SELECT * FROM Families f WHERE f.lastName = @lastName",
  parameters: [
    {name: "@lastName", value: "Hendricks"}
  ]
};
const {result: items} = await items.query(querySpec).fetchAll();

Most of this is based on lines 33-48 here.

1 Answers

COUNT(1) returns a document, with a property representing the count, something like:

SELECT COUNT(1) FROM C
[
    {
        "$1": 123
    }
]

You can alias the $1, with something like:

SELECT COUNT(1) AS MyCount FROM C
[
    {
        "MyCount": 123
    }
]

To return just a scalar value, use VALUE COUNT(1):

SELECT VALUE COUNT(1) FROM c
[
    123
]
Related