问题描述
我有一个对话集合:
{_id: ..., from: userA, to: userB, message: "Hello!", datetime: ...}
我想显示用户对话的预览-当前用户与任何其他用户之间的每次对话的最后一条消息.因此,当用户单击某个最后一条消息"时,他将转到下一页,其中包含他和该用户之间的所有消息.
I want to show a preview of user's conversations - last message from each conversation between current user and any other users. So when user clicks on some "last message" he goes to next page with all messages between him and that user.
在没有Map/Reduce的情况下该如何做(从每个对话中获得1条最后一条消息)?
How do I do that (get 1 last message from each conversation) without Map/Reduce?
1)使用"distinct"命令? (如何?)
1) use "distinct" command? (how?)
2)将"last"标志设置为最后一条消息?我认为这不是很安全...
2) set "last" flag for last message? I think it's not very safe...
3)..?
推荐答案
我正在使用游标和许多高级查询的功能和内容……这令人痛苦且令人困惑.然后我意识到,这很痛苦,因为这不是mongodb希望您真正去做的.
I was writing up a complicated answer to this question using cursors and a lot of advanced query features and stuff... it was painful and confusing. Then I realized, this is painful because it's not how mongodb expects you to do things really.
我认为您应该做的就是对数据进行反规范化,轻松解决这一问题.方法如下:
What I think you should do is just denormalize the data and solve this problem in one shot easily. Here's how:
- 在您的用户上放置一个名为
most_recent_conversations
的哈希/对象字段 -
与其他用户进行新对话时,请对其进行更新,使其看起来像这样:
- Put a hash/object field on your User called
most_recent_conversations
When you make a new conversation with another user, update it so that it looks like this:
previewUser.most_recent_conversations[userConversedWith._id] = newestConversation._id
每次创建新对话时,只需使用较新的对话ID来粉碎其哈希中所涉及的用户的值即可.现在,我们有了一个{ uid: conversationId, ... }
结构,该结构基本上 是我们所需的预览数据.
Every time you make a new conversation, simply smash the value for the users involved in their hashes with the newer conversation id. Now we have a { uid: conversationId, ... }
structure which basically is the preview data we need.
现在,您可以简单地查找最近的对话(如果将哈希的每个值都设为数组,则可以查找N个对话!)
Now you can look up the most recent conversation (or N conversations if you make each value of the hash an array!) simply:
var previewUser = db.users.findOne({ _id: someId });
var recentIds = [];
for( uid in previewUser.most_recent_conversations ) {
recentIds.push( previewUser.most_recent_conversations[uid] );
}
var recentConversations = db.conversations.find({
_id: { $in: recentIds }
});
这篇关于MongoDB-从每个对话中获得1条最后一条消息吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!