我想对mongodb的字段进行排序,其中包含数字(非小数和十进制)。当我简单地对小数进行排序时,即使小数应排在最后,也应排在最前面。我该怎么做才能以正确的顺序进行排序?
答案 0 :(得分:0)
对于以下一组数据
{ "_id" : ObjectId("5c04bb058288944d211a1a6c"), "name" : "a", "id": 0.5 },
{ "_id" : ObjectId("5c04bb058288944d211a1a6d"), "name" : "b", "id" : 1 },
{ "_id" : ObjectId("5c04bb058288944d211a1a6e"), "name" : "c", "id" : 1.5 },
{ "_id" : ObjectId("5c04bb058288944d211a1a6f"), "name" : "d", "id" : 2 }
以下查询按ID的降序对数据进行排序。
db.YourCollection.find().sort({id: -1})
输出
{ "_id" : ObjectId("5c04bb058288944d211a1a6f"), "name" : "d", "id" : 2 },
{ "_id" : ObjectId("5c04bb058288944d211a1a6e"), "name" : "c", "id" : 1.5 },
{ "_id" : ObjectId("5c04bb058288944d211a1a6d"), "name" : "b", "id" : 1 },
{ "_id" : ObjectId("5c04bb058288944d211a1a6c"), "name" : "a", "id" : 0.5 }
使用
.sort({"id": 1})
对数据进行升序排序。