Arranging users based on their highest number of followers in Meteor

Welcome to my Meteor project!

I'm currently working with two collections:

1 - followers

"_id": "_id",
  "follower": "username1",
  "following": "username2"
}

2- users

"_id": "_id",
  "username": "username",
  [...]
}

I am looking to sort users based on the number of followers they have. Can anyone provide guidance on how I can achieve this?

Your help would be greatly appreciated.

Answer №1

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determine the id of every element when scrolling to the top in an Angular application

I am searching for a way to retrieve the id of the section element when it reaches the top. A similar task has been accomplished using jQuery on Stack Overflow, but I am looking to achieve the same with Angular. I have tried a similar approach but without ...

The omission of form field values is causing the Auto POST Form on Interval to be incomplete

There is a script that functions correctly when a button is clicked to submit the form. However, when I change the form to automatically post on an interval, the values in the form fields are not included in the submission. I believe this issue is relate ...

Troubleshooting Problem with ListItem Alignment in Material UI v0 involving Custom Avatar Component

Material UI version: v0.20.0 I'm facing an issue with aligning the leftAvatar value using the CustomAvatar component, as shown in the attached screenshot. Any assistance would be appreciated. CustomAvatar: The functionality of this component is cond ...

Ways to Implement Named Module Exports in Node.js Version 16 Application

Currently, I am working with Node 16.3.0 and Express 4.17.1 (although the Node version is open to change) In my project, I have a file named session.js structured as follows: // session.js exports.fetchUserId = async function(token){ ... } exports.sav ...

Ways to organize backbone models, views, and collections using vim?

I am a fan of vim's folding feature, but I have encountered some challenges when trying to fold backbone models, views, and collections. This is because backbone does not follow the traditional prototype syntax, but instead uses a .extend() based synt ...

Integrating React with the math.js library for enhanced functionality

My React component is having trouble integrating with the math.js library. When I attempt to display the output of the code in the console, everything works fine without resetting the state. However, when I try to use the result of the evaluate() function ...

Unable to interact with a button through Selenium

Utilizing the Selenium library in Java, I have written a script to automate tasks online. The script functions perfectly on popular sites such as Facebook and YouTube, but for some reason, it does not work on kingdoms.com. The button I am trying to click h ...

Using webGL for rendering drawElements

I am working with face-indices that point to specific points to draw triangles in a loop. Unfortunately, when executing my code, I encountered the following error in the web console: WebGL: drawElements: bound element array buffer is too small for given c ...

Step-by-step guide for conducting a Twitter API search in Node.js using a keyword inputted by the user

I am new to Node.js, Express, and Angular. I currently have a Node/Express application running on my local host. My goal is to transform this app into a Twitter search tool by utilizing the Twitter API. I want users to be able to input a search term and re ...

Incorporating the sx attribute into a personalized component

I am currently incorporating MUI v5 along with Gatsby Image in my project. To maintain consistency in my styling syntax throughout the application, I decided to include the sx prop in the GatsbyImage component. This is how I attempted it: <Box compon ...

Transforming a collection of nested objects from Firebase into an array in JavaScript/Typescript

In my Ionic3 / Angular4 application, I am utilizing Firebase. The structure of the data in Firebase Realtime Database is as follows: Using the TypeScript code below, I am fetching observable data from Firebase... getDishesCategories(uid: string) { ...

Tips for adding an array to an array of objects with AngularJs

I'm facing an issue with the array structure in my code. Here's what I currently have: $scope.arrayList=[{FirstName:"",LastName:""}]; $scope.Address=[{address:"",PhoneNumber:""}]; What I want to achieve is to push the $scope.Address array into ...

Mongoose pre-hook problem caused by circular reference

Within my Node and MongoDB backend setup, I am utilizing Mongoose pre and post hook middleware to keep track of changes in the document and generate system notes accordingly. However, I am encountering an issue when attempting to query the record for the ...

How can I retrieve the next AUTO_INCREMENT value using Sequelize?

Is there a way to retrieve the next auto_increment value using Sequelize? Here is the mysql query used: SELECT auto_increment FROM information_schema.tables WHERE table_schema = 'skolboz' AND table_name = "cases"; The resp ...

The Struts2 jsp page is popping up in a separate window instead of loading within the content div

In my Struts2 application, the home page layout consists of a Header, Menu, Content, and Footer sections arranged horizontally. When a menu item is clicked, a "navigate" action is triggered using JQuery and Ajax. The menu name is passed as a parameter to t ...

What is the best way to retrieve the data being saved in the "insertMany" middleware?

I am attempting to encrypt the passwords of a group of users that I am loading with a seeder. While I can access the keys and values in the documentation, I am struggling to modify them before saving. Below is the code I am currently using: UserSchema.pre ...

Why is Laravel giving back UTCDateTime instead of a Carbon instance?

Within my model, I have specified the following dates to be protected: protected $dates = ['created_at','modified_at','deleted_at', 'my_date']; This same model is also integrated into another document using Mongo. ...

How can you optimize the uploading time and bandwidth by a factor of 1/3 when the output of toDataURL is in base64 format?

The purpose of the code snippet below is to compress a 2 MB JPG file to a 500 KB file, and then upload it to a server upon submitting a <form>. By importing an image from a JPG file into a canvas and exporting it using toDataURL, the following JavaS ...

The content was not displayed because the MIME type did not match

I've been facing a persistent error regarding MIME type mismatch for all of my CSS and JavaScript files. The setup I'm currently using involves a node.js server with Express and Express-Handlebars for routing and templates. It seems that the prob ...

Maintaining the functionality of the browser's "back" button by utilizing AJAX/jQuery for page loading and the history.pushState() technique

I'm working on a project where I want to maintain the functionality of the back button when loading pages using AJAX (specifically jQuery's load method) and updating the URL in the browser bar with history.pushState. The issue arises when users c ...