Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb - mongoose, sort by summing two fields

I have a database schema like this:

var User = new mongoose.Schema({
  ...
  points:{
    type: Number
  },
  extraPoints:{
    type: Number
  },
  ...
})

Ok, when I want to sort the database I want to have a filed that sums the two fields like this:

var newFiled = (points*50 + extraPoints);

so when I sort the database I'd do something like this:

model.User.find({}).sort(newFiled).exec();

I've checked out the aggregate but I don't know how to sort it when it's aggregated.
Thanx for help :)

like image 641
Mohsen Shakiba Avatar asked Jan 09 '23 11:01

Mohsen Shakiba


1 Answers

In mongodb aggregation, this can be achieved through the $project operator. The newField is added via the $project operator pipeline stage with the $add arithmetic operator which adds the two fields. The sorting is done through the $sort pipeline step:

var pipeline = [
    {
        "$project": {
            "points": 1,
            "extraPoints": 1,
            "newField": { "$add": [ "$points", "$extraPoints" ] }
    },
    {
        "$sort": { "newField": 1 }
    }            
];

model.User.aggregate(pipeline, function (err, res) {
    if (err) return handleError(err);
    console.log(res); 
});

// Or use the aggregation pipeline builder.
model.User.aggregate()
  .project({
       "points": 1,
       "extraPoints": 1,
       "newField": { "$add": [ "$points", "$extraPoints" ] }
  })
  .sort("newField")
  .exec(function (err, res) {
      if (err) return handleError(err);
      console.log(res); 
});
like image 71
chridam Avatar answered Jan 14 '23 22:01

chridam