E
E
EpicUsaMan2017-06-14 18:13:16
JavaScript
EpicUsaMan, 2017-06-14 18:13:16

MongoDB: How to pull dialogs from messages?

{
_id: 1
from: 12,
to: 24,
msg: "text"
}
There is this kind of entries in mongo, how to find one entry for each to or from value, where the value you are looking for is in from or to and get the msg of the most recent element with found from\to.
That is, let's say a user with id 12, you need to find one message that was written to him or he wrote to some user and get the last message, and so on for each user with whom the person with id 12 interacted. (In fact, pull out dialogs from messages)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2017-06-14
@EpicUsaMan

Something like this:

var a = 12;
db.talks.aggregate([
  {$project:{"_id":1,"from":1, "to":1, "msg":1, "ft":["$from", "$to"]}},
  {$match:{"ft":a}},
  {$unwind: "$ft"},	
  {$match:{"ft":{$ne:a}}},
  {$sort:{"_id":1}},
  {$group: {"_id":"$ft", "orig_id":{$last:"$_id"},"from":{$last:"$from"},
          "to":{$last:"$to"},"msg":{$last:"$msg"}}},
  {$sort:{"_id":1}},
  {$project:{"_id":"$orig_id","from":1, "to":1, "msg":1}}
]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question