$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.

CategoryString
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $strcasecmp: [ <string-expression1>, <string-expression2> ] }

⚙️ Parameters

string 1Required; the first string expression.
string 2Required; 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏