I am trying to write a pipeline query on the following
{
"_id" : 1,
"createdDate" : "2018-01-01 00:00:00",
"visits" : [
{
"date" : "2018-02-01 00:00:00",
"type" : "A",
},
{
"date" : "2018-03-01 00:00:00",
"type" : "B",
}]
"user" : "Alpha"
},
{
"_id" : 1,
"createdDate" : "2018-01-15 00:00:00",
"visits" : [
{
"date" : "2018-02-01 00:00:00",
"type" : "B",
},
{
"date" : "2018-04-08 00:00:00",
"type" : "A",
}]
"user" : "Alpha"
}
I want to
- Group by user
- Get No of Records
- Basis a date filter
- latest type to be selected basis the same date filter
Example:
date between 2018-01-01 and 2018-02-02
Desired Output
{_id:"Alpha",
type: {"A":1, "B":1},
count : 2}
date between 2018-01-01 and 2018-03-02
Desired Output
{_id:"Alpha",
type: {"A":0, "B":2},
count : 2}
Here is where i have got so far
{$match:{ "createdDate":{ "$gte":"2018-01-01 00:00:00",
"$lte":"2018-02-02 23:59:59"}
}
},
{$unwind:"$visits"},
{$match:{ "visits.date":{ "$gte":"2018-01-01 00:00:00",
"$lte":"2018-02-02 23:59:59"}
}
},
{$project:{_id:1, "visit_type":"$visits.type", "visit_date":"$visits.date"}},
{ $group : { _id : "$_id",
"visits" : { "$push": {
"date": "$visit_date",
"type": "$visit_type"
}
}
}
}