$strcasecmp (Case-Insensitive Compare)
Last updated: 2026-10-09
$strcasecmp (Case-Insensitive Compare)
$strcasecmp compares two strings case-insensitively and returns -1, 0, or 1 — handy for sorting, grouping, or conditional logic. It accepts strings only; other types throw. Note it compares code-point order, not natural-language collation: Chinese sorts by Unicode code points, which may differ from pinyin or dictionary order. Either argument null yields null.
| Category | String |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $strcasecmp: [ <string-expression1>, <string-expression2> ] }
⚙️ Parameters
| string 1 | Required; the first string expression. |
|---|---|
| string 2 | Required; the second string expression. |
Returns:Comparison result: -1, 0, or 1; null if either argument is null.
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $strcasecmp: compare against alice ignoring case
db.users.aggregate([
{ $project: { cmp: { $strcasecmp: [ '$name', 'alice' ] } } }
])
Output:
{ "_id": 1, "cmp": 0 }
{ "_id": 2, "cmp": 1 }
📌 Notes
- Case-insensitive: 'ALICE' versus 'alice' yields 0
- Non-string input throws — convert with $toString first
- The sign matches sort direction, so it works as a sort helper
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat does 0 mean?
AThe two strings are equal ignoring case.
QDoes it work for Chinese?
AYes, but it compares code points, not pinyin or dictionary order.
QWhat differs from $cmp?
A$cmp compares case-sensitively in binary order; $strcasecmp ignores case.