【发布时间】:2021-04-12 17:32:15
【问题描述】:
我正在尝试汇总保存的用户会话并获取某个日期范围内每个日期的单个活跃访问者的数量。
我有一个包含以下属性的会话模型:
{
'environment' : ObjectId("xxxxxxxxxxxxxxxxxxxxxxxx"),
'created' : ISODate("2021-01-05T22:02:25.757Z"),
'visitor' : ObjectId("xxxxxxxxxxxxxxxxxxxxxxxx")
}
结果应该是这样的:
[
{
'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...
]
这是我尝试的最后一个管道,当然这是错误的:
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",
}
}
])
我为我的管道尝试了一些我自己的组合和一些 SO 组合,但还没有取得很大的成功。
非常感谢您的帮助。
【问题讨论】:
-
在这里检查非常相似的问题:stackoverflow.com/questions/65603346/…
-
@kiko075 是的,但不是我要找的。 --thx
标签: javascript node.js mongodb mongoose aggregation-framework