MongoDB Concept Analysis
No matter what database we learn, we should learn its basic concepts. In MongoDB, the basic concepts are document, collection, and database, which we will introduce one by one below.
The following table will help you more easily understand some concepts in MongoDB:
| SQL terminology/concept | MongoDB terminology/concept | Explanation/description |
|---|---|---|
| database | database | Database |
| table | collection | Database table/collection |
| row | document | Data record row/document |
| column | field | Data field |
| index | index | Index |
| table joins | Table join, not supported by MongoDB | |
| primary key | primary key | Primary key, MongoDB automatically sets the _id field as the primary key |
Through the following diagram example, we can also more intuitively understand some concepts in Mongo:

Complete list of terms:
-
Document: The basic data unit of MongoDB, usually a JSON-like structure that can contain multiple data types.
-
Collection: Similar to a table in a relational database, a collection is a container for a group of documents. In MongoDB, documents in a collection do not need to have a fixed schema.
-
Database: A MongoDB instance containing one or more collections.
-
BSON: Short for Binary JSON, it is the binary form of JSON that MongoDB uses to store and transfer documents.
-
Index: A data structure used to optimize query performance; indexes can be created based on one or more fields in a collection.
-
Sharding: A method of distributing data across multiple servers (called shards), used to handle large datasets and high-throughput applications.
-
Replica Set: A group of MongoDB servers maintaining the same dataset, providing data redundancy and high availability.
-
Primary: The server in a replica set responsible for handling all write operations.
-
Secondary: A server in a replica set used for reading data and taking over as primary when the primary fails.
-
MongoDB Shell: The command-line interface provided by MongoDB for interacting with MongoDB instances.
-
Aggregation Framework: A series of operations for performing complex data processing and aggregation.
-
Map-Reduce: A programming model for parallel computing on large datasets.
-
GridFS: A specification for storing and retrieving files larger than the BSON document size limit.
-
ObjectId: A unique identifier automatically generated by MongoDB for each document.
-
CRUD operations: Create, Read, Update, Delete operations.
-
Transactions: Supported since MongoDB 4.0, allowing a group of operations to be executed as an atomic unit.
-
Operators: Special fields used to query and update documents.
-
Join: MongoDB allows the use of the
$lookupoperator in queries to implement SQL-like join operations. -
TTL(Time-To-Live): TTL can be set on certain fields in a collection to automatically delete old data.
-
Storage Engine: The underlying technology MongoDB uses for data storage and management, such as WiredTiger and MongoDB's old storage engine MMAPv1.
-
MongoDB Compass: MongoDB's graphical interface tool for visualizing and managing MongoDB data.
-
MongoDB Atlas: A cloud service provided by MongoDB that allows hosting MongoDB databases in the cloud.
Database
Multiple databases can be created in a MongoDB.
If no database is specified during operation, MongoDB uses a default database named test, which is stored in the data directory.
A single MongoDB instance can hold multiple independent databases, each with its own collections and permissions, and different databases are also placed in different files.
Starting from MongoDB 4.0, multi-document transactions on a single database are supported.
"show dbs" command can display a list of all data.
$ ./mongo
MongoDB shell version: 3.0.6
connecting to: test
> show dbs
local 0.078GB
test 0.078GB
>
Executing "db" command can display the current database object or collection.
$ ./mongo
MongoDB shell version: 3.0.6
connecting to: test
> db
test
>
Running the "use" command can connect to a specified database.
> use local
switched to db local
> db
local
>
In the above example command, "local" is the database you want to link to.
In the next chapter we will explain in detail the use of commands in MongoDB.
Databases are also identified by names. A database name can be any UTF-8 string that meets the following conditions.
- Cannot be an empty string ("").
- Must not contain ' ' (space), ., $, /, \, and \0 (null character).
- Should be all lowercase.
- At most 64 bytes.
Some database names are reserved, and you can directly access these databases with special functions.
- admin: From the perspective of permissions, this is the "root" database. If a user is added to this database, the user automatically inherits permissions for all databases. Some specific server-side commands can only be run from this database, such as listing all databases or shutting down the server.
- local: This data is never replicated and can be used to store arbitrary collections limited to a single local server
- config: When Mongo is used in a sharded setup, the config database is used internally to save information related to shards.
Document
A document is a set of key-value pairs (i.e., BSON). MongoDB documents do not need to have the same fields, and the same fields do not need the same data type, which is very different from relational databases and is a very prominent feature of MongoDB.
A simple document example is as follows:
{"site":"www.runoob.com", "name":"Runoob Tutorial"}
The following table lists the corresponding terms in RDBMS and MongoDB:
| RDBMS | MongoDB |
|---|---|
| Database | Database |
| Tables | Union |
| line | Document |
| column | Field |
| Table join | Embedded document |
| Primary key | Primary key (MongoDB provides the key _id) |
| Database server and client | |
| Mysqld/Oracle | mongodb |
| mysql/sqlplus | mongo |
It should be noted that:
- Key/value pairs in a document are ordered.
- Values in a document can be not only strings inside double quotes, but also several other data types (even an entire embedded document).
- MongoDB distinguishes types and case.
- MongoDB documents cannot have duplicate keys.
- Document keys are strings. With a few exceptions, keys can use any UTF-8 characters.
Document key naming conventions:
- Keys cannot contain \0 (null character). This character is used to indicate the end of a key.
- . and $ have special meanings and can only be used in specific contexts.
- Keys starting with an underscore "_" are reserved (not strictly required).
Union
A collection is a group of MongoDB documents, similar to a table in RDBMS (Relational Database Management System).
Collections exist in databases and have no fixed structure, which means you can insert data of different formats and types into a collection, but usually the data we insert into a collection has some relevance.
For example, we can insert the following documents with different data structures into a collection:
{"site":"www.baidu.com"}
{"site":"www.google.com","name":"Google"}
{"site":"www.runoob.com","name":"Runoob Tutorial","num":5}
When the first document is inserted, the collection is created.
Legal collection names
- A collection name cannot be an empty string "".
- A collection name cannot contain the \0 character (null character), which indicates the end of the collection name.
- A collection name cannot start with "system.", which is a prefix reserved for system collections.
- User-created collection names cannot contain reserved characters. Some drivers do support including them in collection names, because some system-generated collections contain this character. Unless you want to access such a system-created collection, never let $ appear in the name.
The following example:
db.col.findOne()
capped collections
Capped collections are collections with a fixed size.
It has high performance and queue-expiration characteristics (expiration follows insertion order), somewhat similar to the "RRD" concept.
Capped collections are high-performance and automatically maintain the insertion order of objects. They are very suitable for log-recording-like functions. Different from standard collections, you must explicitly create a capped collection and specify a size for the collection, in bytes. The data storage space of the collection is allocated in advance.
Capped collections can save documents in the order of insertion, and the storage locations of these documents on disk are also saved in insertion order. Therefore, when we update a document in a capped collection, the updated document cannot exceed the size of the previous document, so as to ensure that the disk locations of all documents remain unchanged.
Since a capped collection determines insertion positions by document insertion order rather than using indexes, this can improve the efficiency of adding data. MongoDB's operation log file oplog.rs is implemented using a Capped Collection.
Note that the specified storage size includes the database header information.
db.createCollection("mycoll", {capped:true, size:100000})
- In a capped collection, you can add new objects.
- Updates can be performed; however, objects do not increase storage space. If they do, the update will fail.
- Using a Capped Collection, you cannot delete a single document, but you can use the drop() method to delete all rows in the collection.
- After deletion, you must explicitly recreate this collection.
- On 32-bit machines, the maximum storage of a capped collection is 1e9 (1X109) bytes.
Metadata
Database information is stored in collections. They use system namespaces:
dbname.system.*
In a MongoDB database, the namespace
| Collection namespace | Description |
|---|---|
| dbname.system.namespaces | List all namespaces. |
| dbname.system.indexes | List all indexes. |
| dbname.system.profile | Contains database profile information. |
| dbname.system.users | List all users who can access the database. |
| dbname.local.sources | Contains server information and status of the replication peer (slave). |
There are the following restrictions on modifying objects in system collections.
Inserting data into {{system.indexes}} can create an index. But otherwise the information in this table is immutable (the special drop index command will automatically update the relevant information).
{{system.users}} is modifiable. {{system.profile}} is deletable.
MongoDB Data Types
The following table shows several commonly used data types in MongoDB.
| Data Type | Description |
|---|---|
| String | String. A commonly used data type for storing data. In MongoDB, only UTF-8 encoded strings are valid. |
| Integer | Integer value. Used to store numbers. Depending on the server you use, it can be 32-bit or 64-bit. |
| Boolean | Boolean. Used to store Boolean values (true/false). |
| Double | Double-precision floating-point value. Used to store floating-point values. |
| Min/Max keys | Compare a value with the lowest and highest values of a BSON (binary JSON) element. |
| Array | Used to store an array or list or multiple values as a single key. |
| Timestamp | Timestamp. Records the specific time a document was modified or added. |
| Object | Used for embedded documents. |
| Null | Used to create a null value. |
| Symbol | Symbol. This data type is basically equivalent to the string type, but the difference is that it is generally used in languages that use special symbol types. |
| Date | Date. Stores the current date or time in UNIX time format. You can specify your own date and time: create a Date object and pass in year, month, and day information. |
| Object ID | Object ID. Used to create the ID of a document. |
| Binary Data | Binary data. Used to store binary data. |
| Code | Code type. Used to store JavaScript code in a document. |
| Regular expression | Regular expression type. Used to store regular expressions. |
The following describes several important data types.
ObjectId
ObjectId is similar to a unique primary key, can be generated and sorted quickly, and contains 12 bytes, meaning:
- The first 4 bytes represent the creation unix timestamp, Greenwich Mean Time UTC time, 8 hours behind Beijing time
- The next 3 bytes are the machine identification code
- The following two bytes consist of the process id, PID
- The last three bytes are a random number

Documents stored in MongoDB must have an _id key. The value of this key can be of any type, and by default it is an ObjectId object.
Since ObjectId stores the creation timestamp, you do not need to save a timestamp field for your document; you can get the document's creation time through the getTimestamp function:
> var newObject = ObjectId()
> newObject.getTimestamp()
ISODate("2017-11-25T07:21:10Z")
Convert ObjectId to string
> newObject.str
5a1919e63df83ce79df8b38f
String
BSON strings are all UTF-8 encoded.
Timestamp
BSON has a special timestamp type for MongoDB's internal use, unrelated to the ordinary Date type. A timestamp value is a 64-bit value, where:
- The first 32 bits are a time_t value (the number of seconds since the Unix epoch)
- The last 32 bits are an incrementing value for operations within a certain second
序数
In a single mongod instance, timestamp values are usually unique.
In a replica set, oplog has a ts field. The value in this field uses a BSON timestamp to represent the operation time.
The BSON timestamp type is mainly used internally by MongoDB. In most application development cases, you can use the BSON Date type.
Date
Represents the number of milliseconds since the Unix epoch (January 1, 1970). The Date type is signed, with negative numbers representing dates before 1970.
> var mydate1 = new Date() //格林尼治时间
> mydate1
ISODate("2018-03-04T14:58:51.233Z")
> typeof mydate1
object
> var mydate2 = ISODate() //格林尼治时间
> mydate2
ISODate("2018-03-04T15:00:45.479Z")
> typeof mydate2
object
The time created this way is of Date type, and you can use the methods of the Date type in JS.
Returns a string of a time type:
> var mydate1str = mydate1.toString()
> mydate1str
Sun Mar 04 2018 14:58:51 GMT+0000 (UTC)
> typeof mydate1str
string
or
> Date()
Sun Mar 04 2018 15:02:59 GMT+0000 (UTC)