我一直在開發一個聊天應用程式,我需要顯示與一個用戶進行對話的用戶串列。更像是Whatsapp的第一個螢屏,其中你有所有給你發短信的用戶的串列。
我的messagesSchema如下:
from : {type : mongoose. Types.ObjectId, ref : "Users"/span>},
到。{type : mongoose.Types.ObjectId, ref : "Users"},
messageType : String。
messageContent :String,
影像。[Object]。
poster : Object,
status : String,
date: { type: Date, default: Date.now }
我使用的是nodejs,我已經嘗試了很多分組,分組和其他mongoose查詢,但都失敗了
。請幫助我進行查詢,以獲得一個人與他們的最后一條資訊進行對話的所有不同的獨特用戶,并填充 "到 "和 "來自"。
uj5u.com熱心網友回復:
資料:
[
{
"_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".
}
]
Aggregate: (you are ObjectId("10000000000000000000"))
db.collection.aggregate( [
{
$match: {
"$or": [
{ "from": ObjectId("100000000000000000") },
{ "to":
]
}
},
{
$project: {
whom: {
$first: {
$filter: {
input: [ "$from", "$to" ],
as: "i"。
cond: { $ne: [ "$i", ObjectId("100000000000000000") ] ]
}
}
}
},
date: 1,
messageContent: 1,
to: 1,
from: 1, from.
}
},
{
$sort: { "date"/span>: -1 }.
},
{
$group: {
_id: "$whom"/span>,
date: { "$first": "$date" },
message: { "$first"/span>: "$messageContent" },
to: { "$first"/span>: "$to" },
from: { "$first"/span>: "$from" }.
}
}
])
結果:
[
{
"_id"。ObjectId("300000000000000000000000"),
"date"。ISODate("2021-09-04T11:23:25.184Z") 。
"訊息"。"333"。
},
{
"_id": ObjectId("200000000000000000000000"),
"date"。ISODate("2021-09-03T11:23:25.184Z") 。
"訊息"。"222"。
}
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/307941.html
標籤:
