我正在尝试编写一个mongo查询,它会在2015年到2016年之间找到最大的排名。这就是我写的,但结果不正确,我不知道如何正确地写这个。
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 :(得分:0)
您可以使用aggregation framework。
更新:如果$match
或2016rank
字段的数据类型不是double或整数,我添加了跳过文档的2015rank
阶段。
代码示例:
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}
}
])