【发布时间】:2019-10-30 17:28:13
【问题描述】:
我收集了从用户那里收到的消息。我想按按时间戳排序的用户名的连续序列对其进行分组。 我有如下所述的收集消息:
{
"_id":ObjectId("AAAA")
"userName":"Krunal"
"message":"Krunal types some text",
"timestamp":ISODate("2019-06-17T11:57:00.000")
}
{
"_id":ObjectId("AAAB")
"userName":"Krunal"
"message":"Krunal types some text again",
"timestamp":ISODate("2019-06-17T11:59:00.000")
}
{
"_id":ObjectId("AAAC")
"userName":"Krunal"
"message":"Krunal types some text one more time",
"timestamp":ISODate("2019-06-17T12:05:00.000")
}
{
"_id":ObjectId("AAAD")
"userName":"Karan"
"message":"Karan type some text",
"timestamp":ISODate("2019-06-17T12:07:00.000")
}
{
"_id":ObjectId("AAAE")
"userName":"Karan"
"message":"Karan type some more text",
"timestamp":ISODate("2019-06-17T12:10:00.000")
}
{
"_id":ObjectId("AAAC")
"userName":"Krunal"
"message":"Krunal types some text one more time",
"timestamp":ISODate("2019-06-17T12:12:00.000")
}
我使用 4 字节的对象 id 使其易于阅读,在实际场景中它将是 mongodb 生成的实际对象 id 从上面的集合中,我想要如下所述的输出:
{
"userName":"Krunal",
"count":3,
"timestamp":ISODate("2019-06-17T12:05:00.000")
}
{
"userName":"Karan",
"count":2,
"timestamp":ISODate("2019-06-17T12:10:00.000")
}
{
"userName":"Krunal",
"count":1,
"timestamp":ISODate("2019-06-17T12:12:00.000")
}
我想统计来自用户名的用户的连续消息 mongodb中是否有可用的查询,或者我需要在简单的查找查询后编写单独的算法?
编辑: 我不想只按用户名分组。我想要的是按用户名与连续文档分组。例如,考虑上面提到的集合。 Krunal 已连续发送 3 条消息,因此 Krunal:3,然后 Karan 已连续发送 2 条消息,因此 Karan:2,现在 Krunal 又发送了一条消息,但在 karan 之后,它将成为新对象,如 Krunal:1,不会增加之前的 Krunal 计数
【问题讨论】:
标签: mongodb mongoose mongodb-query aggregation-framework