Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

MongoDB Concept Analysis

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:


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.

Some database names are reserved, and you can directly access these databases with special functions.


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:

  1. Key/value pairs in a document are ordered.
  2. Values in a document can be not only strings inside double quotes, but also several other data types (even an entire embedded document).
  3. MongoDB distinguishes types and case.
  4. MongoDB documents cannot have duplicate keys.
  5. Document keys are strings. With a few exceptions, keys can use any UTF-8 characters.

Document key naming conventions:


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

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})


Metadata

Database information is stored in collections. They use system namespaces:



dbname.system.*

In a MongoDB database, the namespace .system.* is a special collection (Collection) containing various system information, as follows:

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:

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:

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)