{
"_id": "654f4d7cbb027c35a0b90529",
"msg": "test message",
"createdat": {
"$date": "2023-11-11T09:46:41.872Z"
},
"dateseen": {
"$date": "2023-11-11T09:55:56.596Z"
},
"fromid": "eb78a1f79938f5eb193b63fc13b3250",
"toid": "7b987d98718041abb3b9a85b5c96214a",
"deleted1": false,
"deleted1at": null,
"deleted2": false,
"deleted2at": null,
"type": 1
}
字符串
我有一个查询,其中我以上述格式保存数据。我想通过发送userId来获取用户的消息和最后的消息。我在Golang中为此创建了一个管道,但优化不起作用,在某些情况下消息不会来,等等。
谢谢
我准备的管道;
pipeline := []bson.M{
{
"$sort": bson.M{"createdat": -1},
},
{
"$match": bson.M{
"$or": []bson.M{
{"fromid": userID, "deleted1": false},
{"toid": userID, "deleted2": false},
},
},
},
{
"$group": bson.M{
"_id": bson.M{"$cond": []interface{}{bson.M{"$ne": []interface{}{"$toid", userID}}, "$toid", "$ fromid"}},
"lastMessage": bson.M{"$first": "$$ROOT"},
"unseenCount": bson.M{
"$sum": bson.M{
"$cond": []interface{}{
bson.M{"$and": []interface{}{
bson.M{"$eq": []interface{}{"$toid", userID}},
bson.M{"$eq": []interface{}{"$dateseen", nil}},
}},
one,
0,
},
},
},
},
},
{
"$sort": bson.M{"createdat": -1},
},
{
"$replaceRoot": bson.M{
"newRoot": bson.M{
"$mergeObjects": []interface{}{
"$lastMessage",
bson.M{"unSeenMsgCount": "$unseenCount"},
},
},
},
},
{
"$group": bson.M{
"_id": "$toid",
"lastMessage": bson.M{
"$first": "$$ROOT",
},
},
},
{
"$sort": bson.M{"createdat": -1},
},
{
"$replaceRoot": bson.M{
"newRoot": "$lastMessage",
},
},
{
"$sort": bson.M{"createdat": -1},
},
{
"$skip": offset,
},
{
"$limit": limit,
},
}
cursor, err := r.collection.Collection("user_chats").Aggregate(context.Background(), pipeline)
if err != nil {
return nil, err
}
型
现在的问题是,有时候我发送的userId不会出现在消息列表中,除非最后一条消息属于他/她。我需要更优化的建议。
1条答案
按热度按时间7cjasjjr1#
您的要求对我来说并不完全清楚,但是$setWindowFields可以作为起点:
字符串
Mongo Playground的