Mongodb - 猫鼬,通过对两个字段求和来排序

Mongodb - mongoose, sort by summing two fields

我有这样的数据库模式:

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

好的,当我想对数据库进行排序时,我想要一个将两个字段相加的字段:

var newFiled = (points*50 + extraPoints);

所以当我对数据库进行排序时,我会做这样的事情:

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

我已经查看了聚合,但我不知道聚合时如何排序。
感谢您的帮助:)

在mongodb聚合中,这可以通过$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管道步骤实现:

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