MongoDB $strcasecmp Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $strcasecmp?

$strcasecmp is a MongoDB aggregation expression that compares two strings without regard to letter case. It returns 0 (equal), -1 (first is less), or 1 (first is greater). Behavior is well-defined for ASCII.

Remember
$strcasecmp = case-insensitive string compare for aggregation

{ $strcasecmp: [ <string1>, <string2> ] }

"Active" vs "active" → 0   (equal, ignore case)
"apple"  vs "Banana" → -1  (a < b)
"Zoo"    vs "apple"  → 1   (z > a)

equal check → $eq([ $strcasecmp(...), 0 ])
case-sensitive → use $eq / $cmp instead
UsePrefer
Ignore case when comparing$strcasecmp
Exact case-sensitive match$eq
Force one case, then compare$toLower / $toUpper
Pattern match$regexMatch

How to Use $strcasecmp in MongoDB

Compare two strings, then test the result against 0 when you only care about equality.

  1. Choose an expression stage ($addFields, $project, or $match).
  2. Pass two string expressions to $strcasecmp.
  3. Read -1, 0, or 1 as less / equal / greater (case ignored).
  4. For a boolean match, wrap with $eq: compare the result to 0.
PieceRequired?Role
String 1YesLeft side of the comparison
String 2YesRight side (field or literal)
$eq … 0NoTurn the result into a true/false match

Pseudocode

Pseudocode
for each document:
    a = evaluate(string1)
    b = evaluate(string2)
    // case-insensitive ASCII compare
    if lower(a) < lower(b):
        result = -1
    else if lower(a) > lower(b):
        result = 1
    else:
        result = 0
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while writing case-insensitive comparisons.

TopicDetail
TypeAggregation expression (also usable via $expr)
Syntax{ $strcasecmp: [ <s1>, <s2> ] }
Returns-1 / 0 / 1
Equal check{ $eq: [ { $strcasecmp: [a, b] }, 0 ] }
ASCII noteWell-defined for ASCII strings
Nullsnull equals null (0); a string is greater than null
Sample check$strcasecmp(["Admin", "admin"]) → 0

Live Preview

Watch $strcasecmp compare two strings while ignoring case. Try equal, less, and greater pairs.

Simulates $strcasecmp (same idea as the mongosh examples below).

Result
a = "Admin"
b = "admin"

$strcasecmp → 0  (equal, ignore case)

{ match: true }

Worked Walkthrough — Role Match

A user document stores role: "Admin". We want to know if that matches "admin" without caring about capital letters.

Calculation
Document:
  { name: "Alice", role: "Admin" }

Compare:
  $strcasecmp(["$role", "admin"])

Ignore case:
  "admin" vs "admin" → equal

Result:
  0

Equal check:
  $eq([0, 0]) → true ✓

MongoDB Examples

We store two users with mixed-case roles. First we compare each role to "admin", then we build a boolean isAdmin flag. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine two users: Alice with role Admin, and Bob with role editor. We save them in a collection named users.

mongosh
db.users.insertMany([
  { _id: 1, name: "Alice", role: "Admin" },
  { _id: 2, name: "Bob", role: "editor" }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps two documents in users. Run find() to see them:

mongosh
db.users.find()

Read those documents like this:

Field in MongoDBValuePlain English
role (Alice)"Admin"Capital A — still means admin
role (Bob)"editor"Different role (not admin)
Picture
Target: "admin"

Alice: "Admin"  → ignore case → match → 0
Bob:   "editor" → ignore case → not match → 1
                 (e comes after a)

How It Works

  1. Insert once. insertMany adds Alice and Bob to users.
  2. Case is stored as typed. "Admin" keeps its capital A in the database.
  3. find() shows the same shape. What you inserted is what you get back—ready for $strcasecmp next.

Example 2 — Compare Role to "admin"

Goal: for each user, store the numeric result of comparing role to "admin" while ignoring case.

mongosh
db.users.aggregate([
  {
    $addFields: {
      cmp: {
        $strcasecmp: ["$role", "admin"]
      }
    }
  }
]);

How It Works

  1. Read each role. Alice has "Admin"; Bob has "editor".
  2. Ignore case. $strcasecmp treats "Admin" like "admin".
  3. Alice matches. Result is 0 (equal).
  4. Bob does not. Result is 1 because "editor" sorts after "admin".

Example 3 — Boolean isAdmin Flag

Same data, but wrap $strcasecmp with $eq … 0 so you get true / false instead of -1 / 0 / 1.

mongosh
db.users.aggregate([
  {
    $addFields: {
      isAdmin: {
        $eq: [
          { $strcasecmp: ["$role", "admin"] },
          0
        ]
      }
    }
  }
]);

How It Works

  1. Same stored users. Still using Alice and Bob from Example 1.
  2. Compare ignoring case. $strcasecmp still returns 0 or 1.
  3. Turn into a boolean. $eq checks whether that result is exactly 0.
  4. Easy check. Alice → true; Bob → false.

Edge Cases & Pitfalls

Check these before using $strcasecmp in production pipelines.

not boolean

Result is -1 / 0 / 1

Do not treat the raw result as true/false. For a match flag, compare to 0 with $eq.

ASCII

Well-defined for ASCII

Official docs note well-defined behavior for ASCII. For complex Unicode case rules, consider collation or careful normalization.

null

Null compares as null

null equals null (0). A non-null string is greater than null (1). Missing fields behave like null.

vs $eq

$eq alone is case-sensitive

{ $eq: ["Admin", "admin"] } is false. Use $strcasecmp when case should not matter.

Performance Notes

ApproachCostBest for
$strcasecmp alonePer-document string compareFlags, computed fields
$match + $expr + $strcasecmpExpression filter (not a simple index equality)Case-insensitive filters
Store a normalized fieldIndex-friendly equalityHot case-insensitive lookups

For frequent case-insensitive lookups, a stored lowercase field (or collation) often beats scanning with $expr. Filter early with $match when only some documents need the check.

Key Takeaways

  • Role: case-insensitive string compare → -1/0/1.
  • Equal: result 0 (or $eq with 0 for a boolean).
  • ASCII: well-defined for ASCII strings.
  • Case-sensitive: use $eq instead.

One line: $strcasecmp answers “how do these two strings order if we ignore capital letters?”

Frequently Asked Questions

$strcasecmp compares two strings without regard to letter case. It returns 0 when they match, -1 when the first is less than the second, and 1 when the first is greater. Use it inside aggregation expression stages such as $project and $addFields.
Use { $strcasecmp: [ <string1>, <string2> ] }. Both arguments can be field references like "$status" or literal strings like "active".
Compare the result to zero: { $eq: [ { $strcasecmp: [ "$field", "target" ] }, 0 ] }. That returns true when the strings match case-insensitively.
$eq is case-sensitive: "Active" and "active" are not equal. $strcasecmp ignores case, so those two compare as equal (returns 0).
Yes. Wrap it inside $expr, or use it in an aggregation $match stage. Example: { $expr: { $eq: [ { $strcasecmp: [ "$role", "admin" ] }, 0 ] } }.
Official docs say behavior is well-defined for ASCII. For full Unicode case folding, prefer collation-aware queries or normalize with $toLower / $toUpper carefully for your locale.

Next: $strLenBytes

Count how many UTF-8 bytes a string uses in an aggregation pipeline.

$strLenBytes tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful