Chartjs的MongoDB日志聚合



集合由日志数据组成。

日志

[
{ "Module": "Admin",
"UserEmail": "tony@dne.com",
"Completed": "2020-02-29T01:21:24.128+00:00" },
{ "Module": "Admin",
"UserEmail": "ricky@dne.com",
"Completed": "2020-02-29T01:21:24.128+00:00" },
{ "Module": "Home",
"UserEmail": "ricky@dne.com",
"Completed": "2020-02-29T01:21:24.128+00:00" },
{ "Module": "Admin",
"UserEmail": "santa@dne.com",
"Completed": "2020-02-29T01:21:24.128+00:00" },
{ "Module": "Contact",
"UserEmail": "tony@dne.com",
"Completed": "2020-02-29T01:21:24.128+00:00" },
{ "Module": "Contact",
"UserEmail": "santa@dne.com",
"Completed": "2020-02-29T01:21:24.128+00:00" },
{ "Module": "Admin",
"UserEmail": "ricky@dne.com",
"Completed": "2020-02-29T01:21:24.128+00:00" },
{ "Module": "Home",
"UserEmail": "tony@dne.com",
"Completed": "2020-02-29T01:21:24.128+00:00" }
]

预期结果

[
{
"Module": "Admin",
"Count":4,
"Logs": [
{
"UserEmail": "tony@dne.com",
"Completed": "2020-02-29T01:21:24.128+00:00"
},
{
"UserEmail": "ricky@dne.com",
"Completed": "2020-02-29T01:21:24.128+00:00"
},
{
"UserEmail": "santa@dne.com",
"Completed": "2020-02-29T01:21:24.128+00:00"
},
{
"UserEmail": "ricky@dne.com",
"Completed": "2020-02-29T01:21:24.128+00:00"
}
]
},
{
"Module": "Home",
"Count":2,
"Logs": [
{
"UserEmail": "ricky@dne.com",
"Completed": "2020-02-29T01:21:24.128+00:00"
},
{
"UserEmail": "tony@dne.com",
"Completed": "2020-02-29T01:21:24.128+00:00"
}
]
},
{
"Module": "Contact",
"Count":2,
"Logs": [
{
"UserEmail": "tony@dne.com",
"Completed": "2020-02-29T01:21:24.128+00:00"
},
{
"UserEmail": "santa@dne.com",
"Completed": "2020-02-29T01:21:24.128+00:00"
}
]
}
]

需要对日志进行聚合以获得模块的使用计数,并基于用户的时间插入grpah以获取额外信息。预期结果将用于绘制chartjs中的折线图。

在c@mongodb客户端中查找要为上述问题构建的聚合管道。

您可以使用以下聚合管道来获得所需内容:

db.collection.aggregate([
{
$group: {
_id: "$Module",
Count: {
$sum: 1
},
Logs: {
$push: {
UserEmail: "$UserEmail",
"Completed": "$Completed"
}
}
}
},
{
$project: {
_id: 0,
Module: "$_id",
Count: 1,
Logs: 1
}
}
])

$project阶段仅用于将_id重命名为Module,如果它不相关,则可以将其删除。

你可以在这里测试

最新更新