Today we will write a sample program using MongoDB java driver to sort a collection. Assume that we have a collection like this.
|
C:\Users\sanju.org>mongo MongoDB shell version: 2.2.0 connecting to: test > use cricket switched to db cricket > db.batsman.insert({“name” : “Sachin Tendulkar”, “Tests Played” : 155, “Total Score” : 15000, “Average” : 50.12}) > db.batsman.insert({“name” : “Rahul Dravid”, “Tests Played” : 115, “Total Score” : 12000, “Average” : 48.12}) > db.batsman.insert({“name” : “VVS Laxman”, “Tests Played” : 110, “Total Score” : 11000, “Average” : 38.12}) > db.batsman.find().sort({“Total Score” : 1}) { “_id” : ObjectId(“51503763f410beb3bef16968″), “name” : “VVS Laxman”, “Tests Played” : 110, “Total Score” : 11000, “Average” : 38.12 } { “_id” : ObjectId(“51503749f410beb3bef16967″), “name” : “Rahul Dravid”, “Tests Played” : 115, “Total Score” : 12000, “Average” : 48.12 } { “_id” : ObjectId(“51503727f410beb3bef16966″), “name” : “Sachin Tendulkar”, “Tests Played” : 155, “Total Score” : 15000, “Average” : 50.12 } |
Sorting or ordering by a particular column is really simple using the console, The sort function takes column(s) name and order in which the sorting needs to be done. (-1 == […]
Continue reading…