Mongo:获取具有匹配条件的每个组的第一个文档

时间:2018-11-03 19:00:43

标签: mongodb mongoose

我有带有日期,txt,发送者和接收者的消息模型。我需要获取两个用户之间的最后一条消息,例如:

{_id: 1, sender:1, receiver:2, txt: “hi 2”, date: “2018/04/01”}
{_id: 2, sender:1, receiver:2, txt: “how are you 2”, date: “2018/04/02”}
{_id: 3, sender:2, receiver:1, txt: “hi 1”, date: “2018/04/03”}
{_id: 4, sender:1, receiver:3, txt: “hi 3”, date: “2018/04/01”}
{_id: 5, sender:1, receiver:3, txt: “how are you 3”, date: “2018/04/02”}

如果我要查找涉及用户1的新邮件,则需要:

{_id: 3, sender:2, receiver:1, txt: “hi 1”, date: “2018/04/03”}
{_id: 5, sender:1, receiver:3, txt: “how are you 3”, date: “2018/04/02”}

如果不可能以用户可以成为发送者或接收者的方式对它们进行分组,那么也可以:

{_id: 2, sender:1, receiver:2, txt: “how are you 2”, date: “2018/04/02”}
{_id: 3, sender:2, receiver:1, txt: “hi 1”, date: “2018/04/03”}
{_id: 5, sender:1, receiver:3, txt: “how are you 3”, date: “2018/04/02”}

你们怎么看?可以用mongo / mongoose做到这一点吗?我当时在查看聚合和分组,但是对它们却不太熟悉。

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

boolean x = true;