{
"_id": "654f4d7cbb027c35a0b90529",
"msg": "test message",
"createdat": "2023-11-11T09:46:41.872Z",
"dateseen": "2023-11-11T09:55:56.596Z",
"fromid": "eb78a1f79938f5eb193b63fc13b3250",
"toid": "7b987d98718041abb3b9a85b5c96214a",
"deleted1": false,
"deleted1at": null,
"deleted2": false,
"deleted2at": null,
"type": 1
}
我有一个像上面这样的聊天集合。从这个集合中,我需要一个查询,将某个用户 ID 发送到聊天 DM,并检索最后一条消息的人员、最后一条消息和未读消息的数量。我尝试了很多,但我无法弄清楚。有人可以帮忙吗?
我需要与此类似的输出;
{
"body": [
{
"id": "c5e8b02a94984fe38e7ff35131890b55",
"unSeenMsgCount": 0,
"lastMessage": {
"fromId": "eb78a1f74f274353b63fc13b3250",
"toId": "c5e8b02a94984fe7ff35131890b55",
"message": "string",
"dateSent": 1704889808607,
"type": 1
}
}
],
"header": null
}
这是最接近解决方案的代码,但仍然没有完全满足我的需求。不仅看不见的消息会错误地传入,而且还会从 to id 和 id 返回两个不同的聊天记录。
db.collection.aggregate([
{
$match: {
$or: [
{ "fromid": userID, "deleted1": false },
{ "toid": userID, "deleted2": false }
]
}
},
{
$group: {
_id: {
$cond: {
if: {
$or: [
{ $and: [{ $eq: ["$fromid", userID] }, { $ne: ["$toid", userID] }] },
{ $and: [{ $eq: ["$toid", userID] }, { $ne: ["$fromid", userID] }] }
]
},
then: "$toid",
else: "$fromid"
}
},
lastMessage: {
$last: {
$cond: {
if: {
$or: [
{ $and: [{ $eq: ["$toid", userID] }, { $ne: ["$fromid", userID] }] },
{ $and: [{ $eq: ["$fromid", userID] }, { $ne: ["$toid", userID] }] }
]
},
then: "$$ROOT",
else: null
}
}
},
unseenCount: {
$sum: {
$cond: {
if: {
$and: [
{ $eq: ["$toid", userID] },
{ $eq: ["$dateseen", null] }
]
},
then: 1,
else: 0
}
}
}
}
},
{
$sort: { "lastMessage.createdat": -1 }
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: ["$lastMessage", { "unSeenMsgCount": "$unseenCount" }]
}
}
},
{
$skip: offset
},
{
$limit: limit
}
])
假设你有一个想要查询的 userId 变量,并考虑到你的集合结构,也许你会喜欢这个
db.chats.aggregate([
{
$match: {
$or: [
{ fromid: userId },
{ toid: userId }
],
deleted1: false, // Assuming this flag is for message deletion status
deleted2: false
}
},
{
$sort: { createdat: -1 }
},
{
$group: {
_id: {
$cond: {
if: { $eq: ["$fromid", userId] },
then: "$toid",
else: "$fromid"
}
},
lastMessage: { $first: "$msg" },
unreadCount: {
$sum: {
$cond: [
{ $and: [{ $ne: ["$fromid", userId] }, { $eq: ["$dateseen", null] }] },
1,
0
]
}
}
}
}]);