Implementing String Comparison in MongoDB?

To implement string comparison in MongoDB, use the $strcasecmp operator in aggregation pipelines. It performs case-insensitive comparison of two strings and returns:

  • 1 if first string is "greater than" the second string.

  • 0 if the two strings are equal.

  • -1 if the first string is "less than" the second string.

Syntax

{
    $project: {
        fieldName1: 1,
        fieldName2: 1,
        comparisonResult: { $strcasecmp: ["$field1", "$field2"] }
    }
}

Sample Data

db.demo490.insertMany([
    {"Name1": "John", "Name2": "john"},
    {"Name1": "David", "Name2": "Bob"}, 
    {"Name1": "Carol", "Name2": "Carol"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e8496ccb0f3fa88e22790bb"),
        ObjectId("5e8496d9b0f3fa88e22790bc"), 
        ObjectId("5e8496e5b0f3fa88e22790bd")
    ]
}

Display Sample Data

db.demo490.find();
{ "_id": ObjectId("5e8496ccb0f3fa88e22790bb"), "Name1": "John", "Name2": "john" }
{ "_id": ObjectId("5e8496d9b0f3fa88e22790bc"), "Name1": "David", "Name2": "Bob" }
{ "_id": ObjectId("5e8496e5b0f3fa88e22790bd"), "Name1": "Carol", "Name2": "Carol" }

Example: String Comparison Using $strcasecmp

db.demo490.aggregate([
    {
        $project: {
            Name1: 1,
            Name2: 1,
            Result: { $strcasecmp: ["$Name1", "$Name2"] }
        }
    }
]);
{ "_id": ObjectId("5e8496ccb0f3fa88e22790bb"), "Name1": "John", "Name2": "john", "Result": 0 }
{ "_id": ObjectId("5e8496d9b0f3fa88e22790bc"), "Name1": "David", "Name2": "Bob", "Result": 1 }
{ "_id": ObjectId("5e8496e5b0f3fa88e22790bd"), "Name1": "Carol", "Name2": "Carol", "Result": 0 }

Result Analysis

  • "John" vs "john": Result = 0 (equal, case-insensitive)
  • "David" vs "Bob": Result = 1 ("David" > "Bob" alphabetically)
  • "Carol" vs "Carol": Result = 0 (identical strings)

Conclusion

The $strcasecmp operator provides case-insensitive string comparison in MongoDB aggregation pipelines. Use it within $project stages to compare string fields and get numeric comparison results for further processing.

Updated on: 2026-03-15T03:09:23+05:30

829 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements