I'm trying to aggregate over saved user sessions and get the amount of single active visitors per date in a date range.
I have a session model which contains these properties:
{
'environment' : ObjectId("xxxxxxxxxxxxxxxxxxxxxxxx"),
'created' : ISODate("2021-01-05T22:02:25.757Z"),
'visitor' : ObjectId("xxxxxxxxxxxxxxxxxxxxxxxx")
}
The result should look like this:
[
{
'date' : '2021-01-03',
'count' : 5 // this is the amount of unique visitors. If there are two documents with the same date and visitor id, only one should be count.
},
{
'date' : '2021-01-05',
'count' : 15
},
{
'date' : '2021-01-06',
'count' : 11
},
...etc...
]
This is the last pipeline I tried which of course is wrong:
const data = await Session.aggregate([
{
'$match': {
environment : ObjectID( args.environment ),
created : { '$gte': new Date( args.start ), '$lte': new Date( args.end ) }
}
},
{
$addFields:{
createdDate:{
$dateFromParts:{
year:{
$year:"$created"
},
month:{
$month:"$created"
},
day:{
$dayOfMonth : "$created"
}
}
}
}
},
{
$group:{
_id:{
date:"$createdDate",visitor:"$visitor"
},
count:{$sum:1}
}
},
{
$project:{
_id:0,
date:"$_id.date",
count:"$count",
}
}
])
I tried a few of my own and a few SO combinations for my pipeline but no great success yet.
Help would be very much appreciated.