Use $lookup in nested arrays and objects

Hi
I have the following schema in my mongodb:

Post Schema

{
_id: ObjectId,
text: string,
owner: ObjectId,
comments: {
  count: number,
  entities: [ 
     { 
        owner_id: ObjectId, 
        replies: {
        count: number, entities: [ { owner_id: ObjectId } ]
      }
    } 
  ]
 }
}

Like you can see I have here post and inside of it there is an object called comments witch has a number called count representing the count of comments and an array of comment entities.

the comment entity has an owner_id field and replies object which is very similar to comments object has a count and entities array which containing an owner_id field inside of each element.

my problem here is that i want to populate the owners inside the post and the comments and the replies.

i found a way of doing that by using multiple $unwind and $lookup and $group which tends to be so complicated

so what is the easiest way of doing that user aggregation pipeline.

Thanks.

Hello @Bilal_Azizieh,
In my opinion, there’s not really an easiest to get it done without using $unwind, and $lookup. Because it’s like you put a thing inside a room and you have built 2 doors for that room. If you want that thing later you have to go open 2 doors to get it. There is no other ways. Unless you design with 1 door.

So in your case, to make it simple. you can have a comments collection and you include the post_id into it. Next time when you want to load comments of a specific post you just need to query from Comments collection and find by post_id.
And for replies instead of nested object. You can make query in Comments collection and find by the parent_id

Posts collection

{
    _id: ObjectId,
    text: string,
    owner: ObjectId
}

Comments collection

{
    _id: ObjectId,
    owner_id: ObjectId,
    post_id: ObjectId,
    parent_id: ObjectId, // This is replaced for replies
    
}

I hope this make sense to you. If you have more questions please let me know. :slight_smile: