Search code examples
azure-cosmosdb

How to select all fields of a document and a new property


I am trying to add a new property to the projection of a query using: select *, 4 Type from c, but it fails with error Syntax error, incorrect syntax near ','. Trying select c.*, 4 Type from c results in a similar error: Syntax error, incorrect syntax near '*'.

Projecting all properties manually is not really an option as not all documents contain all properties (one of the best features of DocumentDb).

How can I do so?

UPDATE

What I am trying to accomplish is something very simple in any SQL Like language. Open any relational database of your choosing and execute select *, 4 Type from [Table] and the results are very straight forward: a table with all it's columns and it's corresponding values plus an additional column named Type with all rows having the same value: 4. The difference here is that in a relational database with schema all rows in the database contain the same columns, so it is easy to enumerate the columns instead of asking for *. In a schemaless environment like documentdb you can't enumerate them because there could be unlimited combinations.

I am trying to accomplish the same thing that select c.id, 4 Type from c accomplishes, but with all properties


Solution

  • We solved this issue by adding a User Defined Function:

    function AddType (c, v) { 
       c['Type'] = v;
       return c;
    }
    

    and calling it SELECT value udf.AddType(c,4) FROM c.

    Of course you could make this a little more generic by passing in an array instead, but hopefully the Cosmos Db team will add native support for it.

    WARNING

    This function adds overhead and in our internal tests it more than doubled the RUs. select * from c resulted in 90 RUs vs 220 RUs using the function above.