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:
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.
Let me know if I should have included the model or the rest of my pipeline as well.
CodePudding user response:
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
}
}
...
CodePudding user response:
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' }
},
...