猫鼬-按ID数组查找,但只能检索有限的结果(每个ID 1个)

时间:2020-01-04 15:10:22

标签: javascript arrays node.js mongodb mongoose

我有一个名为“对话”的模型,还有一个名为“消息”的模型,现在我想检索所有带有最后一个消息的对话(每个对话仅1条消息),因此我过滤了对话ID并查询了消息,但是在每次对话中我都无法获取此消息(最后消息)。

let conversations = await ConversationModel.find({});
const conversationIds = conversations.map(conversation => conversation._id)
//  ConversationIds is basically ["conversation1", "conversation2", "conversation3"]

//  Te problem is here, i want to attach the las message for each conversation, if i put limit(1)
//  i will get 1 record for all query, but i want the last message record for each conversation.
MessageModel.find({ _id: { "$in" : conversationIds} }, ...);

1 个答案:

答案 0 :(得分:0)

根据评论中收集的信息;在MessageModel个文档包含用于标识最新文档的时间戳的情况下,可以实现此目的。

想法:通过$match过滤基于conversationIds的消息,并按timestamp进行下一阶段的过滤,其中对话参考上的$group(让我们说conversation_id),然后由$first累加器选择最新的。

汇总查询: playground link

db.collection.aggregate([
  {
    $match: {
      conversation_id: {
        $in: conversationIds
      }
    }
  },
  {
    $sort: {
      timestamp: -1
    }
  },
  {
    $group: {
      _id: "$conversation_id",
      latest_doc: {
        $first: "$$ROOT"
      }
    }
  }
]);