I have googled alot, but not found any helpful solution... I want to find total number of daily users. I have a collection named session_log having documents like following
{
"_id" : ObjectId("52c690955d3cdd831504ce30"),
"SORTID" : NumberLong(1388744853),
"PLAYERID" : 3,
"LASTLOGIN" : NumberLong(1388744461),
"ISLOGIN" : 1,
"LOGOUT" : NumberLong(1388744853)
}
I want to aggregate from LASTLOGIN...
This is my query:
db.session_log.aggregate(
{ $group : {
_id: {
LASTLOGIN : "$LASTLOGIN"
},
count: { $sum: 1 }
}}
);
But it is aggregating by each login time, not by each day. Any help would be appreciated
MongoDB 4.0 and newer
Use
$toDate
or
$convert
MongoDB >= 3.0 and < 4.0:
You would need to convert the
LASTLOGIN
field to a millisecond timestamp through multiplying the value by 1000, then convert to a date
and this can be done in the
$project
pipeline by adding your milliseconds time to a zero-millisecondsDate(0)
object, then extract$year
,$month
,$dayOfMonth
parts from the converted date which you can then use in your$group
pipeline to group the documents by the day.You should thus change your aggregation pipeline to this:
Running the aggregation pipeline:
would give the following results (based on the sample document):
An improvement would be to run the above in a single pipeline as
Running the aggregation pipeline:
First thing is your date is stored in
timestamp
so you need to first converttimestamp
toISODate
using addingnew Date(0)
and multiplytimestamp
to1000
then you will get theISODate
like this :{"$add":[new Date(0),{"$multiply":[1000,"$LASTLOGIN"]}]}
this convert to timestamp to ISODate.Now using date aggregation you need to convert
ISODate
in required format using $concat and then group by final formatting date so aggregation query will be :If you will used mongo version
3.0
and above then use dateToString operator to convertISODate
to predefined format, and aggregation query is :