簡體   English   中英

MongoDB 在 Node.JS mongodb 驅動程序中按自定義計算排序

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

我正在使用 Node.JS MongoDB 驅動程序。 我有一個包含salarynumber of vacancies的工作列表,我想根據一個規則對它們進行排序,如果salarynumber of vacancies數量更大,它們將在排序中獲得最高優先級,我想出了這個簡單的公式

( salary / 100 ) + num_of_vacancies

例如:

最優先的

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

並且優先級較低

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

但我的問題是,據我所知,MongoDB 排序僅需要 arguments 以升序或降序排序,並使用要排序的屬性。 如何使用自定義表達式進行排序。

MongoDB 中的數據如下所示 // 不是完整版本

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

這只是一種選擇。 為 mongo 驅動程序調整它。

  • $addFields我們創建要排序的字段,命名為 toSortLater 只是出於語義目的。
  • 添加一個$sort階段,並首先對高值進行排序。 更改為 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