我正在尝试在以下
上编写管道查询{
"_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"
}
我想
示例:
日期2018-01-01至2018-02-02
期望输出
{_id:"Alpha",
type: {"A":1, "B":1},
count : 2}
日期2018-01-01至2018-03-02
期望输出
{_id:"Alpha",
type: {"A":0, "B":2},
count : 2}
这是我到目前为止的地方
{$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"
}
}
}
}
答案 0 :(得分:1)
您可以尝试以下聚合。
添加了两个组,每个组按类型计数,另一组按用户计数。
[
{"$match":{"createdDate":{"$gte":"2018-01-01 00:00:00","$lte":"2018-03-02 23:59:59"}}},
{"$unwind":"$visits"},
{"$match":{"visits.date":{"$gte":"2018-01-01 00:00:00","$lte":"2018-03-02 23:59:59"}}},
{"$sort":{"visits.date":-1}},
{"$group":{"_id":{"_id":"$_id","user":"$user"},"latestvisit":{"$first":"$visits"}}},
{"$group":{"_id":{"user":"$_id.user","type":"$latestvisit.type"},"visits":{"$sum":1}}},
{"$group":{
"_id":"$_id.user",
"type":{"$push":{"type":"$_id.type","visits":"$visits"}},
"count":{"$sum":"$visits"}
}}
]