【发布时间】:2022-03-19 13:06:02
【问题描述】:
假设我有一个名为 chatMessages 的 mongodb 集合,具有这些属性(在 nodejs 上使用 mongoose):
const schema = {
_id: ObjectID,
chatID: String,
type: String,
message: String,
senderID: String,
date: Date
}
假设我在集合中有 5 个文档:
[
{
_id: 'id1',
chatID: 'alternateChat',
type: 'txt',
message: 'first message',
senderID: 'first_sender_id',
date: new Date('0001-01-02T01:01:11.001Z')
},
{
_id: 'id2',
chatID: 'alternateChat',
type: 'groupedMsgs',
message: 'second message',
senderID: 'first_sender_id',
date: new Date('0001-01-03T01:01:11.001Z')
},
{
_id: 'id3',
chatID: 'alternateChat',
type: 'groupedMsgs',
message: 'third message',
senderID: 'first_sender_id',
date: new Date('0001-01-04T01:01:11.001Z')
},
{
_id: 'id4',
chatID: 'alternateChat',
type: 'txt',
message: 'fourth message',
senderID: 'first_sender_id',
date: new Date('0001-01-05T01:01:11.001Z')
},
{
_id: 'id5',
chatID: 'alternateChat',
type: 'groupedMsgs',
message: 'fifth message',
senderID: 'first_sender_id',
date: new Date('0001-01-06T01:01:11.001Z')
}
]
我想查询这些文档,以便将类型为 groupedMsgs 的连续行(按日期排序)表示为一个,以及在最后一个唯一的 groupedMsgs 中存在的连续行数输出。具体来说,我想要如下所示的输出:
[
{
_id: 'id1',
chatID: 'alternateChat',
type: 'txt',
message: 'first message',
senderID: 'first_sender_id',
date: new Date('0001-01-02T01:01:11.001Z')
},
{
_id: 'id2',
chatID: 'alternateChat',
type: 'groupedMsgs',
message: 'second message',
senderID: 'first_sender_id',
date: new Date('0001-01-03T01:01:11.001Z'),
numConsecutiveItems: 2
},
{
_id: 'id4',
chatID: 'alternateChat',
type: 'txt',
message: 'fourth message',
senderID: 'first_sender_id',
date: new Date('0001-01-05T01:01:11.001Z')
},
{
_id: 'id5',
chatID: 'alternateChat',
type: 'groupedMsgs',
message: 'fifth message',
senderID: 'first_sender_id',
date: new Date('0001-01-06T01:01:11.001Z'),
numConsecutiveItems: 1
}
]
请注意,third message 不在最终输出中,因为它的类型为 groupedMsgs,并连续跟随另一条类型为 groupedMsgs 的消息,而 second message 具有相同的 numConsecutiveItems 或 2原因。更重要的是,fifth message 之所以存在,是因为它不会立即跟随另一个groupedMsgs 消息,并且出于同样的原因,它的numConsecutiveItems 的值是1。什么是可以为我执行此操作的聚合管道?我的偏好是避免使用$accumulator、$function、$where 和$accumulator,以避免在查询期间运行 javascript,因为这会减慢查询操作,但我仍然愿意接受所有答案。
【问题讨论】:
-
每个文档的“_id”值在整个集合中都必须是唯一的。您显示了多个具有相同“_id”的文档。
-
你是对的,这是一个复制粘贴错误。我已经编辑了这些值,使它们都独一无二。
标签: mongodb mongoose mongodb-query aggregation-framework