One approach could be to store the 'followers' collection as an embedded object within each 'users' document instead of keeping them in separate collections. This way, you avoid the need to constantly reference back and forth based on a user's ID, which can end up occupying unnecessary space in your database. Simply create an 'follows' object inside each user containing arrays for 'followers' and 'following', like this:
"users":{
"_id":_id,
"username":"username",
"follows":{
"followers":["username 1","username 2"],
"following":["username 3", "username 4"],
}
}
By structuring each user document with its own 'follows' object, you can easily sort users using MongoDB's 'aggregate' functionality. The below code snippet illustrates sorting by the length of the followers array. A similar process can be done for the 'following' array by substituting '$followers' with '$following':
db.users.aggregate(
[
{
$project: {
"length": { $size: "$followers" }
},
{ "$sort": { "length": -1 } },
}
]
)
This method may require some adjustments depending on your specific requirements, but hopefully, it helps to guide you in the right direction.