how to compare only date part in cosmos db

Viewed 9215

We are storing (EmployeeId,Name,LogDate) data in cosmosdb. LogDate data is Datetime and we want to get data from cosmos where LogDate between '2018-01-15' and '2018-01-30', Means want to compare date part only.

2 Answers

I am from the CosmosDB engineering team. While Jay's answer is an alternative, you could still persist DateTimes as strings in the default ISO 8601 format and create a range index on LogDate. You should be able to do regular comparisons on DateTime like so, using Cosmos DB SQL queries:

SELECT * FROM root where root.LogDate BETWEEN '2018-01-15' and '2018-01-30'

Based on the statements in the official document:

Alternatively, you can store DateTimes as Unix timestamps, that is, as a number representing the number of elapsed seconds since January 1, 1970. Azure Cosmos DB's internal Timestamp (_ts) property follows this approach. You can use the UnixDateTimeConverter class to serialize DateTimes as numbers.

So, I suggest you serializing DateTimes as numbers to compare with the conditions.

You could use User Defined Function in sql:

UDF:

    function convertTime(datetime){
        datetime = datetime.replace(/-/g,'/')  
        if(datetime){
            var date = new Date(datetime);
        }else{
            var date = new Date();
        }
        time1 = date.getTime(); 
        return time1;
    }

SQL:

SELECT c.LogDate FROM c
where udf.convertTime(c.LogDate) > udf.convertTime('2018-01-15') 
and udf.convertTime(c.LogDate) < udf.convertTime('2018-02-20')

Output:

enter image description here

Of course, you could convert the datetime in the code instead of using UDFs.

Related