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.
| Category | BSON Types |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (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
- Stored as UTF-8; index keys have a ~1KB limit
- Never store numbers as strings — sorts will be wrong
- String comparisons are case-sensitive
- Unanchored $regex can't use indexes and scans the collection
🏷️ Related Tags
💡 Related Cases
Deleting Documents and Getting Started with Node.js
Mongoose Models and Schema Design
Mongoose Data Validation and Middleware
📚 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'.