Database
db={"users":[{"_id":ObjectId("5a934e000102030405000001"),name:"user A",},{"_id":ObjectId("5a934e000102030405000002"),name:"user B",},{"_id":ObjectId("5a934e000102030405000003"),name:"user C",},],"conversations":[{"_id":ObjectId("5a934e000102030405000010"),message:"test message AB 1",},{"_id":ObjectId("5a934e000102030405000011"),message:"test message BA 1",},{"_id":ObjectId("5a934e000102030405000012"),message:"test message AB 2",},{"_id":ObjectId("5a934e000102030405000013"),message:"test message AC 1",},{"_id":ObjectId("5a934e000102030405000014"),message:"test message CA 1",},],"lastMessage":[{"_id":ObjectId("5a934e000102030405000020"),from:ObjectId("5a934e000102030405000001"),to:ObjectId("5a934e000102030405000002"),date:new Date("2019-01-01"),conversation:ObjectId("5a934e000102030405000010"),},{"_id":ObjectId("5a934e000102030405000021"),from:ObjectId("5a934e000102030405000002"),to:ObjectId("5a934e000102030405000001"),date:new Date("2019-01-02"),conversation:ObjectId("5a934e000102030405000011"),},{"_id":ObjectId("5a934e000102030405000022"),from:ObjectId("5a934e000102030405000001"),to:ObjectId("5a934e000102030405000002"),date:new Date("2019-01-03"),conversation:ObjectId("5a934e000102030405000012"),},{"_id":ObjectId("5a934e000102030405000023"),from:ObjectId("5a934e000102030405000001"),to:ObjectId("5a934e000102030405000003"),date:new Date("2019-01-02"),conversation:ObjectId("5a934e000102030405000013"),},{"_id":ObjectId("5a934e000102030405000024"),from:ObjectId("5a934e000102030405000003"),to:ObjectId("5a934e000102030405000001"),date:new Date("2019-01-03"),conversation:ObjectId("5a934e000102030405000014"),},]}
Query
db.lastMessage.aggregate([{$match:{$or:[{from:ObjectId("5a934e000102030405000001")},{to:ObjectId("5a934e000102030405000001")}],deletedBy:{$ne:ObjectId("5a934e000102030405000001")}}},{$sort:{date:-1}},{$project:{_id:1,from:1,to:1,conversation:1,date:1}},{$group:{_id:{userConcerned:{$cond:{if:{$eq:["$to",ObjectId("5a934e000102030405000001")]},then:"$to",else:"$from"}},interlocutor:{$cond:{if:{$eq:["$to",ObjectId("5a934e000102030405000001")]},then:"$from",else:"$to"}}},from:{$first:"$from"},to:{$first:"$to"},date:{$first:"$date"},conversation:{$first:"$conversation"}}},{$lookup:{from:"conversations",localField:"conversation",foreignField:"_id",as:"conversation"}},{$unwind:{path:"$conversation"}},{$lookup:{from:"users",localField:"to",foreignField:"_id",as:"to"}},{$unwind:{path:"$to"}},{$lookup:{from:"users",localField:"from",foreignField:"_id",as:"from"}},{$unwind:{path:"$from"}}])