March 29, 2024

The ContactSunny Blog

Tech from one dev to another

Sorting in MongoDB in Java using BasicDBObject

5 min read
In this post, we'll see how we can write a sort query for MongoDB in Java using the BasicDBObject class. I'll use Spring Boot for this.
Wooden order signage

In this post, we’ll see how we can write a MongoDB sort query in Java. Sorting is one of the basic operations we do when querying any database. MongoDB is no different. The database offers sorting on any field in a document, and in any direction. Sorting is relatively easier as well. We’ll use a Spring Boot project (works with any Java project) in this post to see how we can write a sort query in Java for sorting MongoDB documents.


The sample data we are working with

Before we see the Java code, we’ll see the data we’re working with. I created a test database called sortTest and a collection called sampleData. Following is one of the documents in the collection, which I’m presenting here to understand the data structure in the collection:

{
    "_id": ObjectId("5e2ab7026e86f37572cb6a1f"),
    "string1": "41xEe0001n",
    "string2": "7PTNR341LtImEgf151v6",
    "double1": 42.94519047627077,
    "double2": 734.1225639965396
}

As you can see from the document above, it is a very simple document. There are two string fields and two double fields. This is random data that I generated using a random data generator I wrote for MongoDB in Java. You can have a look a the code on my Github repository.

Anyway, now that we know what our data looks like, let’s see how to write a native sort query in MongoDB.


MongoDB sort query

We’ll be sorting on the double1 field, which is the first field of type double in the document. There are 10000 documents in the collection that we’re sorting now. We’ll sort the field double1 in natural order, which is ascending. And we’ll fetch only the first two documents that the query returns, so that we’ll be able to validate the query, and have enough data to look through. We don’t want all 10000 documents. For this, the query is as follows:

db.sampleData.find({}).sort({double1: 1}).limit(2)

The result for this query is as follows:

{
	"_id" : ObjectId("5e2ab7006e86f37572cb5129"),
	"string1" : "Zs99QqiRix",
	"string2" : "HVL6kkcNJ4jhvHWdhpFI",
	"double1" : 0.022157774575192857,
	"double2" : 292.69961792176565
}
{
	"_id" : ObjectId("5e2ab7026e86f37572cb6128"),
	"string1" : "JbR2bfPeZQ",
	"string2" : "VFvXgrqkiIA4l4ZLg44z",
	"double1" : 0.02242889925391589,
	"double2" : 565.718163044074
}

As you can see, the query works. Below is a screenshot of the query in my NoSQL Booster window.

MongoDB Sort Query in NoSQL Booster window

Now that we know the query works, we’ll replicate the same in our Java application.


MongoDB sort query in Java

As usual, we’ll start this Spring Boot project by looking at the properties we have in our application.properties file:

spring.data.mongodb.uri=mongodb://localhost:27017/sortTest

mongo.database.name=sortTest

mongodb.collections.sampleData.name=sampleData

We import these properties in our Java class using the @Value annotation, like this:

@Value("${mongodb.collections.sampleData.name}")
private String sampleDataCollectionName;

@Value("${mongo.database.name}")
private String mongoDatabaseName;

Next, we write a utility class called MongoUtil, which is annotated with the @Component annotation, so that it can be @Autowired. We autowire an instance of the MongoClient class in this class. And in the post-constructor hook, we’ll initialize an instance of the MongoDatabase class which we’ll use to query the MongoDB database. The code till this point looks like this:

@Component
public class MongoUtil {

    private static final Logger logger = LoggerFactory.getLogger(MongoUtil.class);

    @Autowired
    private MongoClient mongoClient;

    private MongoDatabase mongoDatabase;

    @Value("${mongodb.collections.sampleData.name}")
    private String sampleDataCollectionName;

    @Value("${mongo.database.name}")
    private String mongoDatabaseName;

    @PostConstruct
    private void postConstructor() {
        mongoDatabase = mongoClient.getDatabase(mongoDatabaseName);
    }
}

Next, we write a method which we’ll call to run the sort query. But how do we construct the query? Let’s look at that first. We have to create a query object first, using the BasicDBObject class.

BasicDBObject query = new BasicDBObject();

Because we’re not filtering the results based on any query, we’ll not add any query parameters to this object. We’ll create a similar object for the sort() part of the query.

BasicDBObject sort = new BasicDBObject();

We’ll add the sort field and the sort direction to this object, like this:

sort.put("double1", 1);

The only thing left to do now is run the query, we can do that with just one statement like this:

mongoDatabase.getCollection(sampleDataCollectionName).find(query).sort(sort).limit(2);

The complete function looks like this:

public FindIterable<Document> getLowestDouble1Records() {

    BasicDBObject query = new BasicDBObject();

    BasicDBObject sort = new BasicDBObject();
    sort.put("double1", 1);

    return mongoDatabase.getCollection(sampleDataCollectionName).find(query).sort(sort).limit(2);
}

Let’s test this now.


Testing the MongoDB sort query

As I already mentioned, we will autowire the MongoUtil class in our main class, like so:

@Autowired
private MongoUtil mongoUtil;

We simply call the getLowestDouble1Records() method on this object now:

FindIterable<Document> documents = this.mongoUtil.getLowestDouble1Records();

We have the records in the documents variable. We’ll just loop through the list and print the records to validate our query:

for (Document document : documents) {

    if (document != null) {
        logger.info("Fetched document: " + document.toJson());
    }
}

The complete class looks like this:

@SpringBootApplication
public class App implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(App.class);

    @Autowired
    private MongoUtil mongoUtil;

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    @Override
    public void run(String... args) throws Exception {

        FindIterable<Document> documents = this.mongoUtil.getLowestDouble1Records();

        for (Document document : documents) {

            if (document != null) {
                logger.info("Fetched document: " + document.toJson());
            }
        }
    }
}

When you run this program, you should get results similar to the following:

Fetched document: { "_id" : { "$oid" : "5e2ab7006e86f37572cb5129" }, "string1" : "Zs99QqiRix", "string2" : "HVL6kkcNJ4jhvHWdhpFI", "double1" : 0.022157774575192857, "double2" : 292.69961792176565 }
Fetched document: { "_id" : { "$oid" : "5e2ab7026e86f37572cb6128" }, "string1" : "JbR2bfPeZQ", "string2" : "VFvXgrqkiIA4l4ZLg44z", "double1" : 0.02242889925391589, "double2" : 565.718163044074 }

As you can see, the result from the Java code match the result we got from running the query directly in the MongoDB shell. If you want to sort the results in the descending order, just change the 1 in the sort query to -1, like this:

sort.put("double1", -1);

I hope this quick post was helpful. If you are facing any difficulty in this, please leave a comment below and I’ll get back to it as soon as possible. And if you want to take a look at the code directly, head over to my Github repository for the complete Spring Boot project. If you are worried about your data in database, consider encrypting your data in MongoDB with a Spring Boot project.

And if you like what you see here, or on my Medium blog, and would like to see more of such helpful technical posts in the future, consider supporting me on Patreon and Github.

Become a Patron!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.