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}}
]);