How to Perform Case-Insensitive Sorting in MongoDB Using Java?

Struggling with case-sensitive sorting in your MongoDB queries written in Java? You’re not alone. By default, MongoDB sorts data based on character case, placing uppercase letters before lowercase ones. This can lead to unexpected results if you’re aiming for case-insensitive sorting (like having “apple” come before “Banana”).

Fear not! This comprehensive guide will help you with an easy technique for achieving case-insensitive sorting in MongoDB using Java i.e Collations. We’ll learn in detail into this method, helping you conquer your data challenges and ensure your queries return results in the order you expect, regardless of letter case.

Solution

To perform case-insensitive sorting, we use MongoDB’s collation feature. Collation allows us to specify language-specific rules for string comparison, including case insensitivity.

Example

import com.mongodb.MongoClientSettings;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.client.model.Collation;
import com.mongodb.client.model.CollationStrength;

import java.util.Arrays;

public class MongoDBSortExample {
    public static void main(String[] args) {
        // Create a MongoDB client
        MongoClient mongoClient = MongoClients.create(MongoClientSettings.builder()
                .applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress("localhost", 27017))))
                .build());

        // Access the database and collection
        MongoDatabase database = mongoClient.getDatabase("testDB");
        MongoCollection<Document> collection = database.getCollection("testCollection");

        // Insert example documents
        collection.insertMany(Arrays.asList(
            new Document("name", "apple"),
            new Document("name", "Banana"),
            new Document("name", "cherry"),
            new Document("name", "Apple"),
            new Document("name", "banana")
        ));

        // Define the collation with locale "en" and strength 5 (IDENTICAL) for case-insensitive sorting
        Collation collation = Collation.builder()
                .locale("en")
                .collationStrength(CollationStrength.IDENTICAL)
                .build();

        // Create a sort document
        Document sort = new Document("name", 1);

        System.out.println("Before Case-Insensitive Sorting:");
        collection.find().sort(sort).forEach(doc -> System.out.println(doc.toJson()));

        System.out.println("\nAfter Case-Insensitive Sorting:");
        // Perform the find and sort with collation
        collection.find()
                .sort(sort)
                .collation(collation)
                .forEach(doc -> System.out.println(doc.toJson()));

        // Close the client
        mongoClient.close();
    }
}

Output

Default Sorting:

The default sorting is case-sensitive, so the output might look like this:

{ "name": "Apple" }
{ "name": "Banana" }
{ "name": "apple" }
{ "name": "banana" }
{ "name": "cherry" }

Case-Insensitive Sorting With Collation:

With collation applied, the output will be case-insensitive:

{ "name": "apple" }
{ "name": "Apple" }
{ "name": "banana" }
{ "name": "Banana" }
{ "name": "cherry" }

Conclusion

By applying collation in MongoDB queries using Java, we can ensure case-insensitive sorting of our data. This is particularly useful for applications requiring consistent and user-friendly data presentation.

Sharing Is Caring:
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments