String (Text)

Last updated: 2026-10-09

String (Text)

String is MongoDB's most common field type, holding UTF-8 text. Match exactly with `$eq` or by pattern with `$regex`; full-text search needs a text index plus `$text`. Storing numbers or dates as strings makes range queries and sorts lexicographic rather than numeric ('9' sorts after '10'), which silently breaks results.

CategoryBSON Types
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ name: "apple" }
{ name: { $regex: "^app" } }
db.articles.find({ $text: { $search: "mongodb" } })

Returns:The string value itself; queries return matching documents

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// String: regex and full-text search
use shop
db.users.find({ email: { $regex: '@example\\.com$' } })
db.articles.find({ $text: { $search: 'mongodb indexing' } })

Output:

// Users whose email ends with @example.com, plus articles matching mongodb/indexing

📌 Notes

📚 Related Tutorials

❓ FAQ

QWhen to use String vs ObjectId?
AUse String for business identifiers (external IDs, order numbers); ObjectId when you want auto-unique, time-ordered ids.
QCan I index string fields?
AYes. Regular indexes for equality/range, text indexes for full-text search.
QWhy is '9' greater than '10'?
AStrings compare char by char; '9' has a larger code point than '1', so '9' sorts after '10'.
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%

🙏 帮我们做得更好

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

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