Mongodb-猫鼬,通过对两个字段求和来排序 [英] Mongodb - mongoose, sort by summing two fields

查看:79
本文介绍了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 :)

推荐答案

在mongodb聚合中,这可以通过 $project 使用 $add 算术运算符的管道阶段将两个字段相加的运算符.通过 $sort 完成排序>管道步骤:

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-猫鼬,通过对两个字段求和来排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆