How to Sort MongoDB Query Results using Java
Introduction
When you query a MongoDB database, you may want your results to be returned in a certain order. Let’s imagine you have a collection of student names in your database– perhaps you’d like to have them returned in alphabetical order, or maybe you want the results returned sorted by age. No matter what your specific requirements may be, it’s easy to sort your MongoDB results with just a few lines of Java code. In this article, we’ll provide instructions and examples on sorting MongoDB query results using Java.
Prerequisites
Before we can proceed to the Java code, we need to make sure some important prerequisites are met. For this task, there are a few key system requirements:
You must ensure that MongoDB is installed and configured before proceeding, as well as the MongoDB Java driver.
You must also ensure that the latest Java JDK is properly installed and configured before proceeding.
Finally, you need to confirm that MongoDB service is running.
NOTE: For the examples shown in this article, we assume that the MongoDB version used is 4.0 and MongoDB Java Driver is 3.8.2.
Creating a MongoDB Test Dataset
It’s easier to follow along with this tutorial if you’re working with the same data as the examples, so the next step will be to create a small sample dataset. Insert the documents shown below into the collection name of your choice. In this article, we’ll be working with a collection called “restoCollection”:
1 2 3 4 5 6 7 8 9 10 | {"_id":{"$oid":"07156d62f57802807471dd3d"},"name":"Yeshuas Grill","contact":{"phone":"386-555-1234","email":"sunTzuResto@example.org"},"stars":4,"categories":["Pizza","Pasta","Italian","Coffee","Sandwiches"]} {"_id":{"$oid":"07156d62f57802807471dd3b"},"name":"Yumster Delicacy","contact":{"phone":"225-456-0102","email":"yumsterD@example.com"},"stars":3,"categories":["Bagels","Cookies","Sandwiches"]} {"_id":{"$oid":"07156d62f57802807471dd28"},"name":"Abishai Buffet","contact":{"phone":"435-234-0098","email":"Abiduday@example.net"},"stars":4,"categories":["Bagels","Sandwiches","Coffee"]} {"_id":{"$oid":"07156d62f57802807471dd22"},"name":"Pure Coffee","contact":{"phone":"847-585-0171","email":"PureBeauty@example.net"},"stars":4,"categories":["Bakery","Cafe","Coffee","Dessert"]} {"_id":{"$oid":"07156d62f57802807471dd39"},"name":"Raizel Cafeteria","contact":{"phone":"867-555-0102","email":"Raizel@example.com"},"stars":2,"categories":["Pizza","Italian"]} {"_id":{"$oid":"07156d62f57802807471dd3a"},"name":"Hungry Pirate Resto Bar","contact":{"phone":"908-555-045","email":"PirateBar@example.com"},"stars":0,"categories":["Pasta","Italian","Buffet","Cafeteria"]} {"_id":{"$oid":"07156d62f57802807471dd35"},"name":"PHL Best Cusine","contact":{"phone":"644-890-0193","email":"PHLBest@example.net"},"stars":5,"categories":["Coffee","Cafe","Bakery","Chocolates"]} {"_id":{"$oid":"07156d62f57802807471dd41"},"name":"El Nido Resto","contact":{"phone":"123-456-0165","email":"ElNido@example.com"},"stars":0,"categories":["Steak","Seafood"]} {"_id":{"$oid":"07156d62f57802807471dd42"},"name":"The Coffee Shop","contact":{"phone":"456-222-0149","email":"coffeShop@example.org"},"stars":4,"categories":["Bakery","Cookies","Cake","Coffee"]} {"_id":{"$oid":"07156d62f57802807471dd44"},"name":"The Steak Buffet","contact":{"phone":"229-789-0197","email":"SteakBuffet@example.org"},"stars":3,"categories":["Steak","Salad","Chinese"]} |
Connecting to a MongoDB Deployment
Now that we’ve set up our test data, it’s time to turn our attention to the code. We begin by connecting to MongoDB:
1 2 3 | MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017"); MongoDatabase db = mongo.getDatabase("restoDB"); MongoCollection<document> collection = db.getCollection("restoCollection"); |
The code displayed above establishes a connection with the MongoDB deployment and accesses both the database (restoDB) as well as the specified collection (restoCollection).
Sorting MongoDB Query Results in Ascending Order using Java
Next, we’ll use the code shown below to sort the collection of MongoDB documents in ascending order:
1 2 3 4 5 6 7 8 | MongoDatabase db = mongo.getDatabase("restoDB"); MongoCollection<document> restaurants = db.getCollection("restoCollection"); FindIterable<document> cursor = restaurants.find().sort(new BasicDBObject("stars",1)).limit(5); MongoCursor<document> iterator = cursor.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } |
Let’s discuss what’s happening in this code. First, the sort()
method takes a new BasicDBObject
containing the field that we want to sort on. In this case, it’s "stars"
, and the 1
indicates that we want to sort in ascending order. The limit()
method limits the number of documents to be processed within a MongoDB collection– in this example, only 5 documents will be displayed.
The results that are returned should look something like this:
1 2 3 4 5 | Document{{_id=07156d62f57802807471dd3a, name=Hungry Pirate Resto Bar, contact=Document{{phone=908-555-045, email=PirateBar@example.com}}, stars=0, categories=[Pasta, Italian, Buffet, Cafeteria]}} Document{{_id=07156d62f57802807471dd41, name=El Nido Resto, contact=Document{{phone=123-456-0165, email=ElNido@example.com}}, stars=0, categories=[Steak, Seafood]}} Document{{_id=07156d62f57802807471dd39, name=Raizel Cafeteria, contact=Document{{phone=867-555-0102, email=Raizel@example.com}}, stars=2, categories=[Pizza, Italian]}} Document{{_id=07156d62f57802807471dd3b, name=Yumster Delicacy, contact=Document{{phone=225-456-0102, email=yumsterD@example.com}}, stars=3, categories=[Bagels, Cookies, Sandwiches]}} Document{{_id=07156d62f57802807471dd44, name=The Steak Buffet, contact=Document{{phone=229-789-0197, email=SteakBuffet@example.org}}, stars=3, categories=[Steak, Salad, Chinese]}} |
Sorting MongoDB Query Results in Descending Order using Java
Next, we’ll look at code that sorts MongoDB documents in descending order:
1 2 3 4 5 6 7 8 | MongoDatabase db = mongo.getDatabase("restoDB"); MongoCollection<document> restaurants = db.getCollection("restoCollection"); FindIterable<document> cursor = restaurants.find().sort(new BasicDBObject("stars",-1)).limit(5); MongoCursor<document> iterator = cursor.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } |
You’ll see that this code is quite similar to the code in our previous example. Once again, the sort()
method takes a new BasicDBObject
containing the field we’re sorting on– the "stars"
field, in this example. The -1
indicates that we want to sort the results in descending order. The limit()
method limits the number of documents to be processed within a MongoDB collection. For this example, only 5 documents will be displayed.
The results should look like the following:
1 2 3 4 5 | Document{{_id=07156d62f57802807471dd35, name=PHL Best Cusine, contact=Document{{phone=644-890-0193, email=PHLBest@example.net}}, stars=5, categories=[Coffee, Cafe, Bakery, Chocolates]}} Document{{_id=07156d62f57802807471dd22, name=Pure Coffee, contact=Document{{phone=847-585-0171, email=PureBeauty@example.net}}, stars=4, categories=[Bakery, Cafe, Coffee, Dessert]}} Document{{_id=07156d62f57802807471dd3d, name=Yeshuas Grill, contact=Document{{phone=386-555-1234, email=sunTzuResto@example.org}}, stars=4, categories=[Pizza, Pasta, Italian, Coffee, Sandwiches]}} Document{{_id=07156d62f57802807471dd42, name=The Coffee Shop, contact=Document{{phone=456-222-0149, email=coffeShop@example.org}}, stars=4, categories=[Bakery, Cookies, Cake, Coffee]}} Document{{_id=07156d62f57802807471dd28, name=Abishai Buffet, contact=Document{{phone=435-234-0098, email=Abiduday@example.net}}, stars=4, categories=[Bagels, Sandwiches, Coffee]}} |
Conclusion
Whether you’re looking to sort employee names in alphabetical order, or you need to organize a list of inventory based on the amounts in stock, it’s easy to sort your MongoDB query results using a bit of Java code. The examples shown in this article demonstrate that you can sort a field in either ascending or descending order, depending on your specific needs. With the instructions provided in this tutorial, you’ll have no trouble sorting MongoDB query results using Java.
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started