Assuming the _id
field is of type ObjectId, the following query prints the counts by day, in descending order.
The initial match stage will filter documents by "last X days". For example, to process only the past 10 days documents from today, get the past_x_days
in milliseconds and use it in the query:
var past_x_days = 10 * 86400000; // where 86400000 is millis per day (24*60*60*1000)
db.test.aggregate( [
{
$match: {
$expr: {
$gt: [ { $toDate: "$_id" }, { $toDate: { $subtract: [ ISODate(), past_x_days ] } } ]
}
}
},
{
$group: {
_id: { dateYMD: {
$dateFromParts : {
year: { $year: "$_id" },
month: { $month: "$_id" },
day: { $dayOfMonth: "$_id" }
}
} },
count: { $sum: 1 }
}
},
{
$sort: { "_id.dateYMD" : -1 }
},
{
$project: {
_id: 0,
count: 1,
dateDMY: { $dateToString: { date: "$_id.dateYMD", format: "%d-%m-%Y" } }
}
}
] )
The output will look like this:
{ "count" : 2, "dateDMY" : "09-12-2019" }
{ "count" : 3, "dateDMY" : "01-12-2019" }
NOTE: The above query works with MongoDB version 4.0. The query is modified to work with version 3.6:
db.test.aggregate( [
{
$addFields: {
oid_date: { $dateToParts: { date: "$_id" } },
dt_diff: { $subtract: [ ISODate(), past_x_days ] }
}
},
{
$addFields: {
oid_dt_ymd: {
$dateFromParts: {
year : "$oid_date.year",
month : "$oid_date.month",
day: "$oid_date.day"
}
}
}
},
{
$match: {
$expr: {
$gt: [ "$oid_dt_ymd", "$dt_diff" ]
}
}
},
{
$group: {
_id: "$oid_dt_ymd",
count: { $sum: 1 }
}
},
{
$sort: { "_id" : -1 }
},
{
$project: {
_id: 0,
count: 1,
dateDMY: { $dateToString: { date: "$_id", format: "%d-%m-%Y" } }
}
}
])
The following are the ObjectId
s are input (shown here with their corresponding date values).
ObjectId(), Dec 10 2019
ObjectId(), Dec 10 2019
ObjectId("5c6b8f57f3558c2685b0d4e3"), Feb 19 2019
ObjectId("5c6b95a7f3558c2685b0d4e4"), Feb 19 2019
ObjectId("5c6b95a7f3558c2685b0d4e5"), Feb 19 2019
ObjectId("5dd525c60fd48753f98ea39b"), Nov 20 2019
ObjectId("5dd525c60fd48753f98ea39c"), Nov 20 2019
ObjectId("5dd525c60fd48753f98ea3a1"), Nov 20 2019
ObjectId("5dd60eaeae3321b020320583"), Nov 21 2019
And, the variable past_x_days = 30 * 86400000
. The query returns:
{ "count" : 2, "dateDMY" : "10-12-2019" }
{ "count" : 1, "dateDMY" : "21-11-2019" }
{ "count" : 3, "dateDMY" : "20-11-2019" }