You basically use the $concat operator to join strings with multiple conditions, as well as $substr to handle conversions:
"day": { "$concat": [ { "$substr": [ { "$year": "$date" }, 0, 4 ] }, { "$cond": [ { "$lte": [ { "$month": "$date" }, 9 ] }, { "$concat": [ "0", { "$substr": [ { "$month": "$date" }, 0, 2 ] } ]}, { "$substr": [ { "$month": "$date" }, 0, 2 ] } ]}, { "$cond": [ { "$lte": [ { "$dayOfMonth": "$date" }, 9 ] }, { "$concat": [ "0", { "$substr": [ { "$dayOfMonth": "$date" }, 0, 2 ] } ]}, { "$substr": [ { "$dayOfMonth": "$date" }, 0, 2 ] } ]} ] }
Another approach, if you are aggregating a “day,” is to simply use the “epoch” value with the date math:
"day": { "$subtract": [ { "$subtract": [ "$date", new Date("1970-01-01") ] }, { "$mod": [ { "$subtract": [ "$date", new Date("1970-01-01") ] }, 1000 * 60 * 60 * 24 ]} ] }
Any mathematical operation with a date on two date objects results in a difference in milliseconds. Therefore, to convert, use an epoch date as a date object. The resulting value is the "day" for the timestamp value and can be returned to create a date object when processing the results.
Perhaps you could do the same in post-processing with $year and $dayOfYear , as this would also be enough to re-create the date object in client processing