MongoDB Keywords & Reserved Names
Understanding restricted names and special keywords in MongoDB
🔑 MongoDB Reserved Keywords
MongoDB has reserved keywords and naming restrictions that you must follow when creating databases, collections, and fields. Understanding these rules prevents errors and ensures your database schema works correctly with MongoDB's query language and operators.
// ❌ Avoid using reserved keywords
db.collection.find({ $where: "this.age > 18" })
// ✅ Use proper field names
db.users.find({ age: { $gt: 18 } })
Reserved Keyword Categories
Operators
Query and update operators
System Fields
MongoDB internal fields
Special Characters
Characters to avoid
Database Names
Restricted database names
🔹 Query Operators (Reserved)
MongoDB query operators start with a dollar sign ($) and are reserved for database operations. Never use these as field names in your documents, as they have special meaning in queries and will cause conflicts with MongoDB's query syntax.
// Common Query Operators (DO NOT use as field names)
$eq // Equal to
$gt // Greater than
$gte // Greater than or equal
$lt // Less than
$lte // Less than or equal
$ne // Not equal
$in // In array
$nin // Not in array
$and // Logical AND
$or // Logical OR
$not // Logical NOT
$exists // Field exists
$type // Field type check
// ❌ WRONG - Using operator as field name
db.users.insertOne({
name: "John",
$gt: 25 // ERROR: Field name cannot start with $
})
// ✅ CORRECT - Using operators in queries
db.users.find({
age: { $gt: 25 } // Correct usage
})
Result:
✅ Operators work correctly in queries
✅ No field name conflicts
✅ Clear query syntax
🔹 Update Operators (Reserved)
Update operators modify documents and are reserved keywords in MongoDB. These operators control how fields are updated, incremented, or removed. Like query operators, they start with $ and should never be used as field names in your documents.
// Common Update Operators (DO NOT use as field names)
$set // Set field value
$unset // Remove field
$inc // Increment number
$mul // Multiply number
$rename // Rename field
$push // Add to array
$pull // Remove from array
$addToSet // Add unique to array
$pop // Remove first/last array element
// ❌ WRONG - Using operator as field name
db.products.insertOne({
name: "Widget",
$inc: 5 // ERROR: Cannot use $ prefix
})
// ✅ CORRECT - Using operators in updates
db.products.updateOne(
{ name: "Widget" },
{
$inc: { quantity: 5 }, // Increment quantity
$set: { updated: new Date() } // Set updated date
}
)
Result:
✅ Updates execute successfully
✅ Fields modified correctly
✅ No naming conflicts
🔹 System Reserved Fields
MongoDB uses special fields for internal operations and references. The _id field is automatically created for every document as a unique identifier. Other system fields like $db and $ref are used for database references and should not be manually created.
// System Reserved Fields
_id // Unique document identifier (auto-generated)
$db // Database reference
$ref // Collection reference
$id // Reference ID
// ✅ _id is automatically created
db.users.insertOne({
name: "John",
email: "[email protected]"
// _id is added automatically
})
// Result:
{
_id: ObjectId("507f1f77bcf86cd799439011"),
name: "John",
email: "[email protected]"
}
// ✅ You can provide custom _id
db.users.insertOne({
_id: "user123",
name: "Jane"
})
// ❌ AVOID manually creating $db, $ref fields
db.users.insertOne({
name: "Bob",
$db: "mydb" // Not recommended
})
Result:
✅ _id automatically generated or custom
✅ System fields work correctly
✅ Document references maintained
🔹 Field Name Restrictions
MongoDB field names have specific rules to ensure compatibility and prevent errors. Field names cannot start with dollar signs, contain dots, or include null characters. Following these rules ensures your documents work correctly with all MongoDB operations and queries.
// Field Name Rules:
// ❌ Cannot start with $
// ❌ Cannot contain . (dot)
// ❌ Cannot contain null character \0
// ✅ Can use letters, numbers, underscores
// ❌ WRONG - Invalid field names
db.users.insertOne({
$name: "John", // ERROR: Starts with $
"user.email": "[email protected]", // ERROR: Contains dot
"data\0": "value" // ERROR: Contains null
})
// ✅ CORRECT - Valid field names
db.users.insertOne({
name: "John",
user_email: "[email protected]",
firstName: "John",
age_in_years: 25,
isActive: true,
created_at: new Date()
})
// ✅ Nested objects (dots in path, not field name)
db.users.insertOne({
name: "John",
address: {
street: "123 Main St",
city: "Boston"
}
})
// Access nested fields with dot notation
db.users.find({ "address.city": "Boston" })
Result:
✅ Valid field names accepted
✅ Nested objects work correctly
✅ Queries execute successfully
🔹 Database Name Restrictions
Database names in MongoDB must follow specific rules and avoid reserved system databases. Names are case-sensitive, cannot contain special characters, and have a maximum length. System databases like admin, local, and config are reserved for MongoDB's internal use.
// Database Name Rules:
// ✅ Case-sensitive (myDB ≠ mydb)
// ✅ Max 64 characters
// ❌ Cannot contain: / \ . " $ * < > : | ?
// ❌ Cannot be empty
// ❌ Reserved: admin, local, config
// ❌ WRONG - Invalid database names
use my-database // ERROR: Contains hyphen
use my.database // ERROR: Contains dot
use my database // ERROR: Contains space
use admin // Reserved system database
// ✅ CORRECT - Valid database names
use myDatabase
use my_database
use app_production
use userDB2024
// Example: Creating and using a database
use myAppDB
db.users.insertOne({
name: "John",
email: "[email protected]"
})
// Show current database
db.getName() // Returns: myAppDB
// List all databases
show dbs
Result:
✅ Database created with valid name
✅ No conflicts with system databases
✅ Collections work correctly
🔹 Collection Name Restrictions
Collection names must follow similar rules to database names but with additional restrictions. They cannot start with "system." as this prefix is reserved for MongoDB system collections. Choose descriptive, valid names that clearly represent the data stored in each collection.
// Collection Name Rules:
// ✅ Can contain letters, numbers, underscores
// ❌ Cannot start with "system."
// ❌ Cannot contain $ (except for system collections)
// ❌ Cannot be empty
// ✅ Max 120 bytes (including database name)
// ❌ WRONG - Invalid collection names
db.system.users.insertOne({}) // ERROR: Starts with system.
db.my$collection.insertOne({}) // ERROR: Contains $
db["my collection"].insertOne({}) // ERROR: Contains space
// ✅ CORRECT - Valid collection names
db.users.insertOne({ name: "John" })
db.products.insertOne({ title: "Widget" })
db.order_items.insertOne({ qty: 5 })
db.userProfiles.insertOne({ bio: "..." })
db.logs_2024.insertOne({ msg: "Info" })
// Create collection explicitly
db.createCollection("customers")
db.createCollection("invoices")
// List all collections
show collections
Result:
✅ Collections created successfully
✅ No naming conflicts
✅ Clear, descriptive names