根据字段之间的最大改进对mongo进行排序结果

问题描述:

我正在尝试编写一个mongo查询,它会在2015年和2016年之间找到排名上最大的改进。这就是我写的,但结果不正确,我不是确定如何正确写入。根据字段之间的最大改进对mongo进行排序结果

db.car.find({}).sort({"2015rank - 2016rank/2015rank" : -1}).pretty(); 

这是结果

"_id" : ObjectId("5a22c8e562c2e489c5df70fa"), 
    "2016rank" : 1, 
    "Dealershipgroupname" : "AutoNation Inc.?", 
    "Address" : "200 S.W. 1st Ave.", 
    "City/State/Zip" : "Fort Lauderdale, FL 33301", 
    "Phone" : "(954) 769-7000", 
    "Companywebsite" : "www.autonation.com", 
    "Topexecutive" : "Mike Jackson", 
    "Topexecutivetitle" : "chairman & CEO", 
    "Totalnewretailunits" : "337,622", 
    "Totalusedunits" : "225,713", 
    "Totalfleetunits" : "3,738", 
    "Totalwholesaleunits" : "82,342", 
    "Total_units" : "649,415", 
    "Total_number_of _dealerships" : 260, 
    "Grouprevenuealldepartments*" : "$21,609,000,000", 
    "2015rank" : 1 
} 
{ 
    "_id" : ObjectId("5a22c8e562c2e489c5df70fb"), 
    "2016rank" : 5, 
    "Dealershipgroupname" : "Sonic Automotive Inc.?", 
    "Address" : "4401 Colwick Road", 
    "City/State/Zip" : "Charlotte, NC 28211", 
    "Phone" : "(704) 566-2400", 
    "Companywebsite" : "www.sonicautomotive.com", 
    "Topexecutive" : "B. Scott Smith", 
    "Topexecutivetitle" : "CEO", 
    "Totalnewretailunits" : "134,288", 
    "Totalusedunits" : "119,174", 
    "Totalfleetunits" : "1,715", 
    "Totalwholesaleunits" : "35,098", 
    "Total_units" : "290,275", 
    "Total_number_of _dealerships" : 112, 
    "Grouprevenuealldepartments*" : "$9,731,778,000", 
    "2015rank" : 4 
+0

您可以另一个字段添加到您的文档,其评价为'2015rank - 2016rank/2015rank',然后排序该字段。 –

您可以使用aggregation framework为样本。

更新:我添加了$match阶段其跳过的文件如果2016rank2015rank字段的数据类型不是双或整数。

代码示例:

db.car.aggregate([ 
    { 
     $match: { 
      $or: [ 
       {"2016rank": {$type: 1}}, 
       {"2016rank": {$type: 16}} 
      ], 
      $or: [ 
       {"2015rank": {$type: 1}}, 
       {"2015rank": {$type: 16}} 
      ] 
     } 
    }, 
    { 
     $addFields: { 
      "rankIncrease": { 
       $divide:[ 
        { 
         $subtract: ["$2016rank", "$2015rank"] 
        }, 
        "$2015rank" 
       ] 
      } 
     } 
    }, 
    { 
     $sort: {"rankIncrease" : -1} 
    } 
]) 
+0

我收到一个错误“不能$从字符串中减去一个字符串” – Rubiks

+0

我认为某些“2015rank”和/或“2016rank”字段包含字符串数据类型(非整数)。 – Neodan

+0

刚刚看了看json文件看起来像2015年一些排名字段包含问号。跳过这些最好的方法是什么? – Rubiks