Core Concepts
When learning any database system, understanding fundamental concepts is essential. In MongoDB, the primary components are documents, collections, and databases. Below is an overview of these core elements.
The following table helps illustrate key MongoDB terminology:
A single MongoDB instance can host multiple databases. The default database is named "db" and is stored in the data directory. Each database operates independently with its own collections and permissions, stored in separate files.
To view available databases:
show dbs
To display the current database:
db
To switch to a specific database:
use local
Database names must follow these UTF-8 string rules:
- Cannot be empty ("")
- Must not contain spaces, periods, dollar signs, slashes, backslashes, or null characters
- Should be lowercase
- Limited to 64 bytes maximum
Certain reserved database names have special purposes:
- admin: Root-level database granting access to all databases. Server administration commands run from here.
- local: Stores collections that are never replicated across servers.
- config: Contains metadata for sharded cluster configurations.
Documents
Documents consist of key-value pairs stored in BSON format. Unlike relational databases, MongoDB documents within a collection don't require identical fields or matching data types - a defining feature of the platform.
Example document structure:
{
"website": "www.example.com",
"title": "Sample Site"
}
Key considerations for documents:
- Key-value pairs maintain insertion order
- Values support various data types including nested documents
- Type sensitivity and case sensitivity apply
- Duplicate keys are prohibited
- Keys are UTF-8 strings with restrictions on null characters
Naming conventions for document keys:
- Null characters (\0) terminate key parsing
- Periods (.) and dollar signs ($) have special meaning
- Underscore-prefixed keys (_) are conventionally reserved
Collections
Collections group related MongoDB documents, similar to tables in relational systems. Collections exist within databases and offer flexible schemas, allowing varied document structures within the same collection.
Example of inserting diverse documents into one collection:
{"url":"www.site1.com"}
{"url":"www.site2.com","name":"Site Two"}
{"url":"www.site3.com","name":"Site Three","visits":150}
Collections are created automatically upon first document insertion.
Valid collection name requirements:
- Non-empty string
- No null characters
- Must not start with "system."
- User-defined names avoid reserved characters like $
Capped Collections
Capped collections provide fixed-size storage with automatic first-in-first-out behavior, ideal for logging scenarios. Unlike standard collections, capped collections require explicit creation with defined byte limits.
Data maintains disk position based on insertion order, making updates permissible only when the modified document doesn't exceed its original size.
Create a capped collection example:
db.createCollection("logData", {
capped: true,
size: 5242880
})
Characteristics of capped collections:
- New documents can be inserted
- Updates allowed but cannot increase document size
- Individual document deletion prohibited; use drop() for entire collection removal
- Maximum size on 32-bit systems limited to 1GB
System Metadata
Database configuration information resides in system collections using reserved namespaces. Key system collections include:
| Namespace | Purpose |
|---|---|
| dbname.system.namespaces | Inventory of all namespaces |
| dbname.system.indexes | Index definitions |
| dbname.system.profile | Performance profiling data |
| dbname.system.users | User access control records |
| dbname.local.sources | Replication source server information |
Modification restrictions apply:
- {{system.indexes}} allows index creation via insert operations
- {{system.users}} supports modifications
- {{system.profile}} permits deletion
Data Types
MongoDB supports various BSON data types:
| Type | Description |
|---|---|
| String | UTF-8 encoded text values |
| Integer | 32 or 64-bit numeric values |
| Boolean | true/false logical values |
| Double | 64-bit floating point numbers |
| Min/Max Keys | BSON element boundary comparisons |
| Array | List or multiple values underr single key |
| Timestamp | Internal operation timestamps |
| Object | Embedded/nested documants |
| Null | Null value representation |
| Symbol | Language-specific symbol strings |
| Date | UNIX timestamp milliseconds |
| Object ID | Unique 12-byte document identifiers |
| Binary Data | Raw binary storage |
| Code | JavaScript code storage |
| Regular Expresion | Pattern matching expressions |
Important Data Types Explained
ObjectId
ObjectId serves as MongoDB's default _id field value, providing unique identification with efficient generation and sorting capabilities. Structure includes:
- 4 bytes: Unix timestamp (UTC)
- 3 bytes: Machine identifier
- 2 bytes: Process ID
- 3 bytes: Random counter
ObjectId conversion example:
> objectIdValue.valueOf()
5a1919e63df83ce79df8b38f
Extract creation timestamp:
> objectIdValue.getTimestamp()
ISODate("2017-11-25T16:23:02Z")
Strings
All BSON strings utilize UTF-8 encoding.
Timestamps
Special internal timestamp type differs from regular date handling:
- First 32 bits: time_t value (seconds since Unix epoch)
- Last 32 bits: incremental operation counter within second
Typically unique within single mongod instances and used extensively in replication operation logs.
Dates
Standard date representation counts milliseconds since Unix epoch (January 1, 1970). Negative values represent pre-1970 dates.
> var currentDate = new Date()
> currentDate
ISODate("2023-12-15T08:30:45.123Z")
> var utcDate = ISODate()
> utcDate
ISODate("2023-12-15T08:30:45.456Z")
Convert date objects to readable strings:
> currentDate.toString()
"Fri Dec 15 2023 08:30:45 GMT+0000 (UTC)"
> String(currentDate)
"Fri Dec 15 2023 08:30:45 GMT+0000 (UTC)"