我需要按降序排列,即从最大值到最小值。 我将使用limit()方法.i需要从整个记录中按降序排序
以下是我使用的以下查询。
db.collection.find( {}, { count: 1 } ).sort({count:-1}).pretty()
这是我的结果--->
{ "_id" : ObjectId("57f62403c058f4135b44f034"), "count" : "6" }
{ "_id" : ObjectId("57f55578a815b9261077890a"), "count" : "5" }
{ "_id" : ObjectId("57f55b3ca815b9261077890c"), "count" : "5" }
{ "_id" : ObjectId("57f62223c058f4135b44f033"), "count" : "5" }
{ "_id" : ObjectId("57f551a4c2a2a1bc0cf37305"), "count" : "4" }
{ "_id" : ObjectId("57f6098cc46b062251260b5d"), "count" : "3" }
{ "_id" : ObjectId("57f55bd5a815b9261077890d"), "count" : "3" }
{ "_id" : ObjectId("57f6185f18b088915615f132"), "count" : "2" }
{ "_id" : ObjectId("57f61b01c058f4135b44f028"), "count" : "2" }
{ "_id" : ObjectId("57f61ee5c058f4135b44f02d"), "count" : "2" }
{ "_id" : ObjectId("57f61f58c058f4135b44f02e"), "count" : "2" }
{ "_id" : ObjectId("57f620cec058f4135b44f030"), "count" : "2" }
{ "_id" : ObjectId("57f6213dc058f4135b44f031"), "count" : "2" }
{ "_id" : ObjectId("57f621a6c058f4135b44f032"), "count" : "2" }
{ "_id" : ObjectId("57f54de0c2a2a1bc0cf37304"), "count" : "18" }
{ "_id" : ObjectId("57f53e15abfe951509221c57"), "count" : "17" }
{ "_id" : ObjectId("57f61df5c058f4135b44f02c"), "count" : "15" }
{ "_id" : ObjectId("57f54bcec2a2a1bc0cf37303"), "count" : "15" }
{ "_id" : ObjectId("57f6179d18b088915615f131"), "count" : "12" }
{ "_id" : ObjectId("57f551cfc2a2a1bc0cf37306"), "count" : "11" }
Type "it" for more
> it
{ "_id" : ObjectId("57f61c85c058f4135b44f02a"), "count" : "10" }
{ "_id" : ObjectId("57f61d63c058f4135b44f02b"), "count" : "1" }
{ "_id" : ObjectId("57f61a29c058f4135b44f026"), "count" : "1" }
{ "_id" : ObjectId("57f618ebc058f4135b44f023"), "count" : "1" }
{ "_id" : ObjectId("57f61a6bc058f4135b44f027"), "count" : "1" }
{ "_id" : ObjectId("57f6094ec46b062251260b5c"), "count" : "1" }
{ "_id" : ObjectId("57f61bc7c058f4135b44f029"), "count" : "1" }
{ "_id" : ObjectId("57f559c4a815b9261077890b"), "count" : "1" }
{ "_id" : ObjectId("57f6202cc058f4135b44f02f"), "count" : "1" }
{ "_id" : ObjectId("57f54362abfe951509221c5a"), "count" : "0" }
{ "_id" : ObjectId("57f619e3c058f4135b44f025"), "count" : "0" }
{ "_id" : ObjectId("57f56721252a87ad13d1f1c6"), "count" : "0" }
{ "_id" : ObjectId("57f619a0c058f4135b44f024"), "count" : "0" }
{ "_id" : ObjectId("57f54a95c2a2a1bc0cf37302"), "count" : "0" }
{ "_id" : ObjectId("57f55fb4a815b9261077890e"), "count" : "0" }
上面的结果不是按降序排列???为什么??
答案 0 :(得分:2)
由于你的count字段是一个字符串,你可以填写所有这些字符串前导0,如01,02,03 ......或者你可以先将它们解析为一个整数,然后对它进行排序:
db.collection.find( {}, { count: 1 } ).forEach(function(doc) {
db.collection.update({ _id: doc._id },{ $set: { count: parseInt(doc. count)} )}).sort({count:-1}).pretty()