【问题标题】:Mongodb - mongoose, sort by summing two fieldsMongodb - 猫鼬,通过对两个字段求和进行排序
【发布时间】:2023-03-08 23:03:01
【问题描述】:

我有一个这样的数据库架构:

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

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

var newFiled = (points*50 + extraPoints);

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

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

我已经检查了汇总,但我不知道汇总后如何对其进行排序。
感谢您的帮助:)

【问题讨论】:

    标签: mongodb sorting mongoose mongodb-query aggregation-framework


    【解决方案1】:

    在mongodb聚合中,这可以通过$project操作符来实现。 newField 是通过 $project 运算符管道阶段添加的,$add 算术运算符添加了两个字段。排序是通过$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); 
    });
    

    【讨论】:

    • 感谢 looooot :) 我希望我能投票给你两次。
    • @user3425760 不用担心,很乐意提供帮助:-)
    猜你喜欢
    • 2016-05-03
    • 1970-01-01
    • 2019-10-30
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 2017-06-03
    • 2019-06-19
    相关资源
    最近更新 更多