0

This is the json for our message document

{ recipient: 5485ef86028950a880f7f878,
  from: 5485ef86028950a880f7f878,
  message: 'Hello! Thank you for looking at my question on StackOverflow!',
  date: Tue Dec 23 2014 16:24:08 GMT-0600 (CST),
  _id: 5499eb8814615b66212018bb }

To view the inbox, I query { recipient: id } and get all the messages to that person. When a user clicks a message, I'd like it to open up a conversation where it queries every single message {from : sender } and { recipient: logged in user } sorted by date. My question is if there's any specific way to model this so that there's a conversation back and fourth, or am I doing this right?

I guess I just described how you'd get an entire conversation history with two users back and fourth, but how would you get an inbox where it only shows the most recent message from every person who sent you a message?

And when you view the conversation, how would you only load the most recent 50 messages or something in the conversation?

UX Guy
  • 257
  • 2
  • 13
  • Hope this helps: - http://stackoverflow.com/questions/26725658/listing-the-last-message-of-each-conversation-involving-an-user-in-mongodb/26747130#26747130 – BatScream Dec 26 '14 at 21:16

1 Answers1

2

I think your model is pretty good. More embedding is often recommended (ex: have a conversations collection where messages is a subdocument), but I think your model works well. For better disambiguation, i would use recipient and sender, rather than recipient and from.

get the 100 most recent messages sent to $user:

db.msgs.find({recipient: $user}).sort({date: -1}).limit(100);

get an entire conversation, sorted by oldest to newest:

db.msgs.find({"$or":[
    {recipient: $user, from: $from},
    {recipient: $from, from: $user}
]}).sort({date: 1});

get the last 50 messages in a conversation:

db.msgs.find({"$or":[
    {recipient: $user, from: $from},
    {recipient: $from, from: $user}
]}).sort({date: -1}).limit(50);
code_monk
  • 9,451
  • 2
  • 42
  • 41
  • 1
    In this case since a thread can be much larger than 16meg it would be a bad idea, also fragmentation would be terrible on this collection making for extremely unperformant queries, also the IO associated with loading all pages of the conversation would apply to one pages since the document still has to be loaded into memory since $slice is only in memory making for a nasty working set. – Sammaye Dec 26 '14 at 21:48
  • agreed. those who recommend embedding subdocuments as a panacea against lack of support for joins, overlook those kinds of problems. As I said, the OPs model works well. It's what I would use. – code_monk Dec 26 '14 at 22:43