sorting - Mongoose 按功能排序

标签 sorting mongoose

我有一个看起来像这样的架构

var user = new Schema({
  preference1: { // preference is a number between 1 - 10
    type: Number 
  },
  preference2: { // preference is a number between 1 - 10
    type: Number 
  }
})

如何找到文档并按首选项字段中的函数排序?说 fn 是这样的

fn = Math.abs(preference1 - 3) + preference2 ^ 2

最佳答案

我找到了一个临时解决方案。它有效,但并不是我真正想要的...代码真的很乱,显然您不能随意使用 fn 进行排序..

例如,说 fn = (a+3) * (b+5)

Media.aggregate()
.project({
     "type": 1,
     "status": 1,
     "newField1": { "$add": [ "$type", 3 ] },
     "newField2": { "$add": [ 5, "$status" ] },
})
.project({
     "newField3": { "$multiply": [ "$newField1", "$newField2" ] },
})
.sort("newField3")
.exec()

关于sorting - Mongoose 按功能排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38387772/

相关文章:

python - 对无序连续整数进行排序的最小交换

java - 如何在 Java 中对表数据结构中的数据进行排序?

node.js - Mongoose 模式验证

angularjs - 是否可以使用带有表单搜索查询输入文本的 Angular Controller 通过 Mongoose 在 MongoDB 中进行实时搜索?

javascript - 我收到重复 key 错误 -- MongoError : E11000 duplicate key error collection. 我确实有 2 个集合、用户和个人资料。

javascript - 使用虚拟属性访问 Mongoose 模型中的嵌套文档

Python:根据两个属性对列表进行排序

python - 按日期对 Python 对象列表进行排序

javascript - 我不明白为什么数字排序函数在 Javascript 中有效

node.js - mongodb schema.createIndex 不是一个函数