Ajeet Ujjwal
Ajeet Ujjwal

Reputation: 133

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

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?

Upvotes: 0

Views: 260

Answers (2)

vishnu
vishnu

Reputation: 2011

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);
  }
);

Upvotes: 2

Travis
Travis

Reputation: 207

It will be in your router, not in Mongoose. Mongoose is used to adhere a standard when writing to the database, not receiving information from it.

It will likely end up being something like this.

movieRouter
    .route("/")
    .get((req, res, next) => {
        Movie.find()
            .then((movies) => {
                res.statusCode = 200;
                res.setHeader("Content-Type", "application/json");
                res.json(movies);
            })
            .catch((err) => next(err));
    })

Upvotes: 1

Related Questions