here is the query
[
{
"$project": {
"formattedDate": {
"$dateToString": { "format": "%Y-%m-%d", "date": "$ceatedAt" }
},
"createdAtMonth": { "$month": "$ceatedAt" },
"rating": 1
}
},
{
"$group": {
"_id": "$formattedDate",
"average": { "$avg": "$rating" },
"month": { "$first": "$createdAtMonth" },
}
}
]
I need the date in timestamp. How to do that?
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
How does Date Query work in MongoDB? We can use date () command to get a date as a string in a query without the new keyword or MongoDB shell. While creating a new date object, we can specify the date object as follows.
Timestamps. BSON has a special timestamp type for internal MongoDB use and is not associated with the regular Date type. This internal timestamp type is a 64 bit value where: the most significant 32 bits are a time_t value (seconds since the Unix epoch)
MongoDB stores times in UTC by default, and will convert any local time representations into this form. Applications that must operate or report on some unmodified local time value may store the time zone alongside the UTC timestamp, and compute the original local time in their application logic.
Mongodb 4.0 has introduced $toLong
aggregation which convert date to timestamp
db.collection.aggregate([
{ "$project": {
"createdAt": {
"$toLong": "$createdAt"
}
}}
])
You can try it here
Use $subtract
arithmetic aggregation operator with your Date as minuend and new Date("1970-01-01")
as subtrahend.
db.collection.aggregate(
{
$project: { "timestamp": { $subtract: [ "$createdAt", new Date("1970-01-01") ] } }
}
);
For document
{ "_id": 1, "createdAt": ISODate("2016-09-01T14:35:14.952Z") }
the result is
{ "_id": 1, "timestamp": NumberLong("1472740514952") }
If you want to group both by timestamp and (year, month, date) you can divide timestamp by the amount of milliseconds in a day, so that it will be unique for each day (and not for each millisecond)
db.collection.aggregate(
{
$project:
{
"timestampByDay":
{
$floor:
{
$divide:
[
{ $subtract: [ "$createdAt", new Date("1970-01-01") ] },
24 * 60 * 60 * 1000
]
}
},
"date": "$createdAt"
}
},
{
$group:
{
"_id": "$timestampByDay",
"date": { $first: "$date" }
}
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With