[Fixed] How to get a list of movies sorted by popularity (favourited by most users) in mongoDB?

Issue

I have following schema for a movie api project.

var MovieSchema = new Schema({
    title: {
        type: String,
        required: true
    },
    description: {
        type: String
    },
    genre: {
        type: String
    },
    release_date: {
        type: Date,
        required: true
    }
});
const userSchema = new Schema({
    name: { type: String, required: true },
    email: { type: String, required: true, unique: true },
    password: { type: String, required: true, minlength: 6 },
    favourite_movies: [{
        type: Schema.Types.ObjectId,
        ref: "Movie"
    }]
});

Please note that schema is hard to change because of other feature restrictions of project.

How to get a list of all movies sorted by popularity (favourited by most users) for this schema?

Solution

You can use the aggregate pipeline for this. Can try something like

MovieModel.aggregate(
  [
    {
      $lookup: {
        from: "users", // user collection name
        localField: "_id",
        foreignField: "favourite_movies",
        as: "user",
      },
    },
    {
      $addFields: {
        count: { $size: "$user" },
      },
    },
    {
      $sort: { count: -1 },
    },
    {
      $unset: ["user", "count"],
    },
  ],
  (err, data) => {
    if (err) console.log(err);
    else console.log(data);
  }
);

Leave a Reply

(*) Required, Your email will not be published