如何获取用户对话的最后一条消息并将其分组在mongodb中的列表中

我想获取一个用户和另一个用户之间的最后一条消息,该消息在一个名为聊天的集合中,所有成员之间都有对话,但我想过滤以便只有一个用户和另一个用户之间的最后一条消息出现。有什么办法可以在 mongodb 中得到这个吗?

例如,我想获取为用户 Carlos 发送/接收的最后一条消息。我想要一个这样的列表

示例:

Chat between John Doe and me
John Doe: Hi

Chat between Max and me
Max: Hello

Chat between jessica and me
Owner: Hello jessica

型号

1. owner = ObjectId
2. recipient = ObjectId
3. content = Message content
4. createdAt / updatedAt = Autogenerate

我目前正在尝试此操作,但错误是我收到了收到给用户的最后一条消息以及用户发送给该用户的最后一条消息

我正在尝试的代码

const chatData = await this.chatModel
  .find({ $or: [{ owner: userId },{ recipient: userId }] })
  .populate('owner',DEFAULT_POPULATE_SELECT_USER)
  .populate('recipient',DEFAULT_POPULATE_SELECT_USER)
  .sort({ createdAt: 'desc' })
  .select({ __v: false })
  .lean();

const chatLog: ChatModel[] = chatData.reduce((unique,item: any) => {
  if (!item.recipient) return unique;
  return unique.some((x) => x.recipient._id == item.recipient._id) ? unique : [...unique,item];
},[]);
eqiu3333 回答:如何获取用户对话的最后一条消息并将其分组在mongodb中的列表中

试试这个查询

示例用户架构

{
    _id: ObjectId,name: String,createdAt: Date,updatedAt: Date
}

示例聊天架构

{
    owner: ObjectId,recipient: ObjectId,content: String
    createdAt: Date,updatedAt: Date
}

查询

const userId = ObjectId('xxxx...')
await chatModel.aggregate([
    { $match: { $or: [ { owner: userId },{ recipient: userId }] } },{ $addFields: {
        me: { $cond: [ { $ne: [ '$owner',userId ] },'$recipient','$owner' ] },other: { $cond: [ { $ne: [ '$owner','$owner','$recipient' ] },} },{ $group: { _id: { me: '$me',other: '$other' },document: { $last: '$$ROOT' } } },{ $replaceRoot: { newRoot: '$document' } },{ $lookup: { from: 'users',let: { owner: '$owner' },as: 'ownerInfo',pipeline: [ { $match: { $expr: { $and: [ { $eq: [ '$_id','$$owner' ] } ] } } } ] } },{ $unwind: '$ownerInfo' },let: { recipient: '$recipient' },as: 'recipientInfo','$$recipient' ] } ] } } } ] } },{ $unwind: '$recipientInfo' },{ $sort: { createdAt: -1 } }
])
本文链接:https://www.f2er.com/8382.html

大家都在问