mongodb的排序方法

1. mongodb 的sort() 方法

语法

#按照key1进行升序排列
db.COLLECTION_NAME.find().sort({key1:1})
#按照key1进行降序排列
db.COLLECTION_NAME.find().sort({key1:-1})

实例

#查询myCollection集合按age字段降序排列
> db.myCollection.find({}).sort({"age":-1})
{ "_id" : ObjectId("5a913296113385ab59f380b5"), "name" : "xxx", "age" : 54 }
{ "_id" : ObjectId("5a91328a113385ab59f380b4"), "name" : "hhh", "age" : 28 }
{ "_id" : ObjectId("5a903519d5f9a583d52a7f7b"), "name" : "ddd", "age" : 19 }
{ "_id" : ObjectId("5a9034fdd5f9a583d52a7f78"), "name" : "eee", "address" : "万年花城" }
{ "_id" : ObjectId("5a90352b113385ab59f380b2"), "name" : "wfei" }
{ "_id" : ObjectId("5a903546113385ab59f380b3"), "name" : "ccc" }


#查询myCollection集合按age字段升序排列
> db.myCollection.find({}).sort({"age":1})
{ "_id" : ObjectId("5a9034fdd5f9a583d52a7f78"), "name" : "eee", "address" : "万年花城" }
{ "_id" : ObjectId("5a90352b113385ab59f380b2"), "name" : "wfei" }
{ "_id" : ObjectId("5a903546113385ab59f380b3"), "name" : "ccc" }
{ "_id" : ObjectId("5a903519d5f9a583d52a7f7b"), "name" : "ddd", "age" : 19 }
{ "_id" : ObjectId("5a91328a113385ab59f380b4"), "name" : "hhh", "age" : 28 }
{ "_id" : ObjectId("5a913296113385ab59f380b5"), "name" : "xxx", "age" : 54 }
    原文作者:非文666
    原文地址: https://www.jianshu.com/p/5f1ed6601775
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞