我一直在开发一个聊天应用程序,我需要显示与用户对话的用户列表。更像whatsapp的第一个屏幕,其中有所有发短信的用户的列表。
我的messagesSchema如下:
from : {type : mongoose.Types.ObjectId, ref : "Users"},
to : {type : mongoose.Types.ObjectId, ref : "Users"},
messageType : String,
messageContent :String,
images : [Object],
poster : Object,
status : String,
date: { type: Date, default: Date.now }我正在使用nodejs,我尝试过很多农耕、group和其他猫鼬查询,但都失败了。
请帮助我查询,以获得所有不同的独特用户,一个人一直在与他们的最后一条消息交谈,并填充' to‘和’从‘。
发布于 2021-09-16 01:03:23
数据:
[
{
"_id": ObjectId("100000000000000000000000"),
"from": ObjectId("100000000000000000000000"),
"to": ObjectId("200000000000000000000000"),
"date": ISODate("2021-09-03T11:23:25.184Z"),
"messageContent": "111"
},
{
"_id": ObjectId("200000000000000000000000"),
"from": ObjectId("200000000000000000000000"),
"to": ObjectId("100000000000000000000000"),
"date": ISODate("2021-09-02T11:23:25.184Z"),
"messageContent": "222"
},
{
"_id": ObjectId("300000000000000000000000"),
"from": ObjectId("300000000000000000000000"),
"to": ObjectId("100000000000000000000000"),
"date": ISODate("2021-09-04T11:23:25.184Z"),
"messageContent": "333"
},
{
"_id": ObjectId("400000000000000000000000"),
"from": ObjectId("300000000000000000000000"),
"to": ObjectId("400000000000000000000000"),
"date": ISODate("2021-09-05T11:23:25.184Z"),
"messageContent": "444"
}
]聚合:(您是ObjectId("100000000000000000000000"))
db.collection.aggregate([
{
$match: {
"$or": [
{ "from": ObjectId("100000000000000000000000") },
{ "to": ObjectId("100000000000000000000000") }
]
}
},
{
$project: {
whom: {
$first: {
$filter: {
input: [ "$from", "$to" ],
as: "i",
cond: { $ne: [ "$$i", ObjectId("100000000000000000000000") ]
}
}
}
},
date: 1,
messageContent: 1,
to: 1,
from: 1
}
},
{
$sort: { "date": -1 }
},
{
$group: {
_id: "$whom",
date: { "$first": "$date" },
message: { "$first": "$messageContent" },
to: { "$first": "$to" },
from: { "$first": "$from" }
}
}
])结果:
[
{
"_id": ObjectId("300000000000000000000000"),
"date": ISODate("2021-09-04T11:23:25.184Z"),
"message": "333"
},
{
"_id": ObjectId("200000000000000000000000"),
"date": ISODate("2021-09-03T11:23:25.184Z"),
"message": "222"
}
]示例: 蒙古操场
https://stackoverflow.com/questions/69198813
复制相似问题