简体   繁体   English

MongoDB 在 Node.JS mongodb 驱动程序中按自定义计算排序

[英]MongoDB sort by custom calculation in Node.JS mongodb driver

I'm Using Node.JS MongoDB driver.我正在使用 Node.JS MongoDB 驱动程序。 I have a collection of job lists with salary and number of vacancies , I want to sort them according to one rule, if either salary or number of vacancies are greater they will get top priority in sorting, and I came up with this simple formula我有一个包含salarynumber of vacancies的工作列表,我想根据一个规则对它们进行排序,如果salarynumber of vacancies数量更大,它们将在排序中获得最高优先级,我想出了这个简单的公式

( salary / 100 ) + num_of_vacancies

eg:例如:

Top priority ones最优先的

{ salary: 5000 , num_of_vacancies: 500 }   // value is 550
{ salary: 50000 , num_of_vacancies: 2 }    // value is 502

And Less priority for并且优先级较低

{ salary: 5000 , num_of_vacancies: 2 }     // value is 52

But my Problem is, As far as I know, MongoDB sort takes arguments only to sort in ascending or descending order and a property to sort.但我的问题是,据我所知,MongoDB 排序仅需要 arguments 以升序或降序排序,并使用要排序的属性。 How do I sort with custom expression.如何使用自定义表达式进行排序。

The data in MongoDB looks like this // not the full varsion MongoDB 中的数据如下所示 // 不是完整版本

{
    title:"job title",
    description:"job description",
    salary:5000,
    num_of_vacancy:50
}

This is just an option.这只是一种选择。 Adjust it for a mongo driver.为 mongo 驱动程序调整它。

  • $addFields we create the field to sort, named toSortLater just for semantic purposes. $addFields我们创建要排序的字段,命名为 toSortLater 只是出于语义目的。
  • add a $sort stage, and sort high values first.添加一个$sort阶段,并首先对高值进行排序。 Change to 1 for the opposite behaviour.更改为 1 以获得相反的行为。
db.collection.aggregate([{
$addFields:{ 
toSortLater:{
   $add:[
       {$divide:["$salary", 100]}, 
       "$num_of_vacancies"]
}}}, {$sort:{"toSortLater":-1}}
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM