I'm trying to create a MongoDB query where I get a conversation between two users. Basically my conversation object is like the following:
{
"_id" : ObjectId("123"),
"from" : ObjectId("456"),
"to" : ObjectId("789"),
"content" : "Hi!",
"createdAt" : 1558037545568.0
}
I wanna bring up their conversation sorted by createdAt descending and also bring their user objects together. I know I need to use a $lookup for search on the users query, but I have some questions:
- How I can create a
$lookupoperation that will bring both of the users? - How to manage it in the way that sometimes the user
456is thefromuser and sometimes thetouser? Same for the user789. I didn't get it too much.
This is the current query that brings everything ordered without the user objects:
db.getCollection('messages').aggregate([{
$match: {
$or: [
{ from: ObjectId("456") },
{ to: ObjectId("789") },
{ from: ObjectId("789") },
{ to: ObjectId("456") }
]
}
}, {
$sort: { createdAt: -1 }
}])
Thank y'all for the help!