mongodb在查询中排序?

mzmfm0qo  于 2022-12-12  发布在  Go
关注(0)|答案(1)|浏览(135)

我需要按降序(即从最大值到最小值)获取计数。我将使用limit()方法。我需要按降序对所有记录进行排序。
下面是我使用的查询。

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" }

以上结果不按降序排列?为什么?

ycl3bljg

ycl3bljg1#

由于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()

相关问题