找到你要的答案

Q:Mongodb - mongoose, sort by summing two fields

Q:MongoDB -猫鼬,总结两个字段排序

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 :)

我有这样的数据库架构:

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

好,当我想对数据库进行排序时,我想有一个字段来概括这两个字段:

var newFiled = (points*50 + extraPoints);

所以当我整理数据库时,我会这样做:

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 :)

answer1: 回答1:

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

在MongoDB中聚集,这可以通过为项目运营商实现。这个新的领域是通过项目运营商管道阶段美元美元加算术运算符将两个领域。排序是通过$排序管道步骤完成的:

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); 
});
mongodb  sorting  mongoose