skip to Main Content

I’m trying creating a query to fetch a user’s friends list. I already have a solution to this problem, but my method involves using project on every single field in the nested array, so I’m looking for the best way to do it. After retrieving all the data I need, the pipeline data looks like this:
enter image description here

From here, I have taken the following steps:

....
.unwind("$user_friends")
.project({
    user_id: "$user_friends.user_id",
    profile_picture: "$user_friends.profile_picture",
    mutual_friend_count: "$user_friends.mutual_friend_count",
    is_friend: "$user_friends.is_friend",
    full_name: "$user_friends.full_name",
})
.sort({ mutual_friend_count: -1 });

This is the result, as well as how I want my data to be formatted.
enter image description here

Let me know if I should have included the model or the rest of my pipeline as well.

2

Answers


  1. I don’t know the mongoose syntax, but you can merge your nested document with ROOT and replace the ROOT with merged document.

    ....
    {
        $unwind: "$user_friends"
    },
    {
        $replaceRoot: { newRoot: { $mergeObjects: [ "$user_friends", "$$ROOT" ] } }
    },
    {
        $project: {
            "user_friends": 0
        }
    }
    ...
    
    Login or Signup to reply.
  2. I think $unwind and $project are not even needed in this case.
    You can use an aggregation pipeline to replace the root (first with the first element of the initial array and then with the ‘user_friends’ attribute).

    ...
    {
        $replaceRoot: { newRoot: { $arrayElemAt: [ "$$ROOT", 0] } }
    },
    {
        $replaceRoot: { newRoot: '$user_friends' }
    },
    ...
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search