0

I have a collection with messages looking like this:

{
        "_id" : ObjectId("593929aa070f5e2f8ce60a1c"),
        "by" : "User1",
        "to" : "testAccount",
        "userImage" : "0cddd4ieiLdtrwerrbabad9a4353330725712fe3b1348239",
        "time" : NumberLong("1496918441854"),
        "text" : "Hello there",
        "type" : 0
}

This collection represents the messages which user can send. And now I want to display a list of chats for each user, like whatsapp. For this I want to get only the last message of this chat (to or by = "User1"). What's the best way to do this? Something with group?

Or is there a better way instead of getting just the last one? Because I think it's better in performance than getting more of it.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
user6586661
  • 432
  • 1
  • 11
  • 24
  • `.find({ "$or": [{ "by": "User1" },{ "to": "User1" }]).sort({ "time": -1 }).limit(1)`. No need to aggregate. It's the fastest way. – Neil Lunn Jun 09 '17 at 14:59
  • @NeilLunn I think you missunderstood my question or it wasn't clear enough. I want only one message for each chat. If I have a chat with Person X, Y and Z I want the last message for each of this persons. And for this you need group I think. – user6586661 Jun 09 '17 at 15:07

0 Answers0