“sort”
method is used to sort documents. To specify sorting order 1 and -1 are used. 1
is used for ascending order while -1 is used for descending order.
Syntax
db.collection_name.find().sort({KEY:1})
> db.employee.find() { "_id" : ObjectId("54b348e01deb1f5f980626a2"), "id" : 1, "firstName" : "Joel", "lastName" : "chelli" } { "_id" : ObjectId("54b348e01deb1f5f980626a3"), "id" : 2, "firstName" : "Ananad", "lastName" : "Bandaru" } { "_id" : ObjectId("54b348e01deb1f5f980626a4"), "id" : 3, "firstName" : "Gopi", "lastName" : "Battu" } { "_id" : ObjectId("54b348e01deb1f5f980626a5"), "id" : 4, "firstName" : "Ritwik", "lastName" : "Mohenthy" } > > > db.employee.find().sort({"firstName" : 1, "lastName" : -1}) { "_id" : ObjectId("54b348e01deb1f5f980626a3"), "id" : 2, "firstName" : "Ananad", "lastName" : "Bandaru" } { "_id" : ObjectId("54b348e01deb1f5f980626a4"), "id" : 3, "firstName" : "Gopi", "lastName" : "Battu" } { "_id" : ObjectId("54b348e01deb1f5f980626a2"), "id" : 1, "firstName" : "Joel", "lastName" : "chelli" } { "_id" : ObjectId("54b348e01deb1f5f980626a5"), "id" : 4, "firstName" : "Ritwik", "lastName" : "Mohenthy" } > > > db.employee.find().sort({"lastName" : -1}) { "_id" : ObjectId("54b348e01deb1f5f980626a2"), "id" : 1, "firstName" : "Joel", "lastName" : "chelli" } { "_id" : ObjectId("54b348e01deb1f5f980626a5"), "id" : 4, "firstName" : "Ritwik", "lastName" : "Mohenthy" } { "_id" : ObjectId("54b348e01deb1f5f980626a4"), "id" : 3, "firstName" : "Gopi", "lastName" : "Battu" } { "_id" : ObjectId("54b348e01deb1f5f980626a3"), "id" : 2, "firstName" : "Ananad", "lastName" : "Bandaru" }
Prevoius Next Home
No comments:
Post a Comment