Mongodb - mongoose, sort by summing two fields Mongodb - mongoose, sort by summing two fields mongoose mongoose

Mongodb - mongoose, sort by summing two fields


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