CoderSathi
  • Tutorial
    • Java Tutorial
    • Swing Tutorial
    • JDBC Tutorial
    • Java String Tutorial
    • Servlet and JSP Tutorial
  • Mongo DB
  • AWS
  • DevOps
  • Linux
  • Git
Home > Java > How to Perform Case-Insensitive Sorting in MongoDB Using Java?

Java Tutorial Menu

  • Introduction
    • What is Java
    • History Of Java
    • Install Java
    • What is JVM
    • JDK vs JRE vs JVM
    • Java Bytecode
    • OOP vs POP
    • Compile and Run Java
  • Tokens, Expressions and Control Structures
    • Primitive data types
    • Integers
    • Floating Points
    • Characters
    • Booleans
    • User Defined Data Type
    • Declarations
    • Constants
    • Identifiers
    • Literals
    • Type Conversion and Casting
    • Variables
    • Default Variable Initialization
    • Command Line Arguments
    • Arrays of Primitive Types
    • Comment Syntax
    • Garbage Collection
    • Expressions
    • Operators
    • Arithmetic Operator
    • Bitwise and Shift Operator
    • Comparison or Relational Operators
    • Logical Operators
    • Assignment Operators
    • Ternary Operator
    • Increment and Decrement Operator
    • Control Statements
  • OOP Concepts
    • Class and Object
    • Create Class Instance
    • Method
    • Abstraction
    • Encapsulation
    • this keyword
    • Constructor
    • Pass by Value
    • Access Modifier/Control
    • Polymorphism
    • Method Overloading vs Method Overriding
    • Recursion
    • Nested and Inner Class
  • Inheritance and Packaging
    • Inheritance
    • extends Keyword
    • super Keyword
    • Object Class
    • Abstract class
    • Final Class
    • Java Package
    • Interface
  • Handling Error/ Exceptions
    • What is Exception
    • Exception Handling Keywords
    • Common Java Errors
    • User Defined Exception
    • Throwing and re-throwing Exception
    • finally Block
  • Strings
    • Java String Tutorial
  • Threads
    • Introduction
    • Create Thread
    • Thread Lifecycle
    • Thread Priority
    • Thread Synchronization
    • Inner Thread Communication
    • Thread Deadlock
  • IO and Streams
    • java.io Package
    • Files and Directories
    • Byte Stream
    • Character Stream
    • Console Input and Output
    • Serializable and Deserializable
  • Core Packages
    • java.lang Package
    • Math
    • Wrapper Classes
    • java.lang.Number
    • Double
    • Float
    • Integers
    • java.lang.Byte
    • java.lang.Short
    • java.lang.Long
    • java.lang.Character
    • java.lang.Boolean
    • java.util package
    • Vector Class
    • Stack Class
    • Dictionary Class
    • Hashtable
    • Enumeration or Enum
    • Generate Random Number
  • Holding Collection of Data
    • Arrays
    • Map
    • List
    • Set
    • Collection Interface
    • Collections Class
    • ArrayList
    • HashSet
    • TreeSet
    • Comparator
  • Java Bean
    • What is Java Bean
    • Advantages and Disadvantages of Java Bean
    • Java Beans API
    • Introspection
    • Java Bean Properties
    • Bound and Constrained Properties
    • BeanInfo Interface
    • Customizers
    • Java Beans Persistence
    • BeanDescriptor

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

Learn the concepts, implementation details, and practical steps with a clean developer-focused walkthrough.

Yuba Raj Kalathoki
By Yuba Raj Kalathoki
Published: May 18, 2024 ยท 2 min read ยท 0 Comments
Share: X in ๐Ÿ”—

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.

Table of Contents

  • Solution
    • Example
    • Output
    • Default Sorting:
    • Case-Insensitive Sorting With Collation:
  • Conclusion

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.

Related Posts:

  • java.lang.Character Class in Java
  • Character data type in Java
  • Control Statements in Java
  • Consistency and Availability in Distributed System
  • Character Stream in Java
  • Identifiers in Java
Tags:javamongodb
Was this article helpful?
โ† Previous ArticleHow to Read Text from Image in Java?
Next Article โ†’Send Java Object as Request Parameter Using Feign Client

Leave a Comment Cancel reply

You must be logged in to post a comment.

Recent Posts

  • How to Use AWS CloudFront Signed URLs in Spring Boot?
  • How to Fix SSH Agent Forwarding on macOS: The Ultimate Guide for Developers
  • How to Read AWS Secrets Manager in Spring Boot (Step-by-Step)
  • How to Fix “Public Key Retrieval is not allowed” MySQL JDBC Error
  • Complete Guide to JaCoCo: How to Measure Java Code Coverage Accurately
CoderSathi

Your go-to resource for Java, Spring Boot, Microservices, AWS, and modern development tutorials.

Quick Links

  • About
  • Contact

Popular Topics

  • Java
  • Spring Boot
  • AWS
  • DevOps
  • MongoDB
  • Linux
  • Git
  • How to
ยฉ 2026 CoderSathi. All rights reserved. Privacy Policy ยท Sitemap