I need to count all users, users from last week and last month, grouping by date.
I've tried
var project = {
$project:{
day: { $dayOfMonth: "$updatedAt" },
month: { $month: "$updatedAt" },
year: { $year: "$updatedAt" }
}
},
group = {
"$group": {
"_id": {
"date": "$updatedAt",
},
"count" : { "$sum" : "$1" }
}
};
db.collection.aggregate([project, group])...
I need to result look like
{lastWeek: 12, lastMonth: 20, all: 102}
EDIT added sample json data. Included only necessary properties of objects for testing
[{
"_id" : ObjectId("someId"),
"createdAt" : ISODate("2017-04-08T09:51:44.897Z"),
"updatedAt" : ISODate("2018-01-08T09:51:55.460Z"),
"foo1" : null
},{
"_id" : ObjectId("someId"),
"createdAt" : ISODate("2017-04-08T09:51:44.897Z"),
"updatedAt" : ISODate("2017-12-30T09:51:55.460Z"),
"foo1" : null
},{
"_id" : ObjectId("someId"),
"createdAt" : ISODate("2017-04-08T09:51:44.897Z"),
"updatedAt" : ISODate("2018-01-17T09:51:55.460Z"),
"foo1" : null
},{
"_id" : ObjectId("someId"),
"createdAt" : ISODate("2017-04-08T09:51:44.897Z"),
"updatedAt" : ISODate("2018-01-01T09:51:55.460Z"),
"foo1" : null
},{
"_id" : ObjectId("someId"),
"createdAt" : ISODate("2017-04-08T09:51:44.897Z"),
"updatedAt" : ISODate("2017-04-08T09:51:55.460Z"),
"foo1" : null
}]
You can try below aggregation
var today = new Date();
var lastWeek = new Date();
today.setDate(today.getDate() - 7);
var lastMonthFromToday = new Date();
lastMonthFromToday.setMonth(today.getMonth() - 1);
db.col.aggregate(
{"$group":{
"_id":null,
"lastWeek":{"$sum":{"$cond":[{$and:[{"$gte":["$updatedAt",lastWeek]}, {"$lte":["$updatedAt",today]}]}, 1, 0]}},
"lastMonth":{"$sum":{"$cond":[{$and:[{"$gte":["$updatedAt",lastMonthFromToday]}, {"$lte":["$updatedAt",today]}]}, 1, 0]}},
"all":{"$sum":1}
}})
Mongo 3.4 version:
db.col.aggregate(
{"$facet":{
"lastWeek":[{"$match":{"updatedAt":{"$gte":lastWeek, "$lte":today}}},{"$count":"count"}],
"lastMonth":[{"$match":{"updatedAt":{"$gte":lastMonthFromToday, "$lte":today}}},{"$count":"count"}],
"all":[{"$count":"count"}]
}})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.