Query ISODate on MongoDB with Google Sheets “dd-MM

2020-04-21 01:47发布

问题:

I use a tool called Redash to query (in JSON) on MongoDB. In my collections dates are formulated in ISO, so when my query is imported (with google sheets' importdata function) to a sheet, I have to convert it to the appropriate format with a formula designed in the sheet. I would love to integrate this operation directly in my query, that the ISO date format is directly sent to Sheets in the appropriate "dd-MM-yyyy HH:ss" format.

Any ideas ?

Many many thanks

回答1:

You may be able to use the $dateToString aggregation operator inside a $project aggregation stage.

For example:

> db.test.find()
{ "_id": 0, "date": ISODate("2018-03-07T05:14:13.063Z"), "a": 1, "b": 2 }

> db.test.aggregate([
    {$project: {
        date: {$dateToString: {
            format: '%d-%m-%Y %H:%M:%S',
            date: '$date'
        }},
        a: '$a',
        b: '$b'
    }}
])
{ "_id": 0, "date": "07-03-2018 05:14:13", "a": 1, "b": 2 }

Note that although the $dateToString operator was available since MongoDB 3.0, MongoDB 3.6 adds the capability to output the string according to a specific timezone.