Home > OS >  Mongoose Order Populars By Total Rating
Mongoose Order Populars By Total Rating

Time:09-06

I want to get popular products from MongoDB. Here is my schema;

  ...
  user: {
    type: mongoose.Types.ObjectId,
    ref: 'users'
  },
  rating: [{
    user : {
      type: mongoose.Types.ObjectId,
      ref: 'users'
    },
    rate: {
      type: Number,
      min: 1,
      max: 5
    }
  }],
  created_at : {
    type : Date
  },
  ...

I want to order by rating.rate sum. How can I do that?

CodePudding user response:

Here a solution:

db.collection('products').aggregate([
  {
    "$unwind": "$rating"
  },
  {
    $group: {
      _id: "$_id",
      sum: {
        "$sum": "$rating.rate"
      },
      
    }
  },
  {
    "$sort": {
      "sum": -1
    }
  }
])

  • Related