MongoDB tutoria...login
MongoDB tutorial
author:php.cn  update time:2022-04-21 17:49:03

MongoDB concept analysis


No matter what database we study, we should learn the basic concepts. The basic concepts in mongodb are documents, collections, and databases. Let’s introduce them one by one below.

The following table will help you understand some concepts in Mongo easier:

SQL terms/conceptsMongoDB terms/conceptsExplanation/Explanation
databasedatabaseDatabase
tablecollectionDatabase table/collection
rowdocumentData record row/document
columnfieldData field/field
indexindexIndex
table joins Table join, MongoDB does not support
primary keyprimary keyPrimary key, MongoDB automatically sets the _id field as the primary key

Through the example below, we can also understand some concepts in Mongo more intuitively:


Database

A mongodb Multiple databases can be created.

MongoDB's default database is "db", which is stored in the data directory.

A single instance of MongoDB can hold multiple independent databases, each with its own collection and permissions. Different databases are also placed in different files.

"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
>

Execute the "db" command to display the current database object or collection.

$ ./mongo
MongoDB shell version: 3.0.6
connecting to: test
> db
test
>

Run the "use" command to 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 name. The database name can be any UTF-8 string that meets the following conditions.

  • cannot be an empty string ("").

  • must not contain ' ' (space), ., $, /, \ and \0 (space character).

  • should be all lowercase.

  • Maximum 64 bytes.

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

  • admin: From a permissions perspective, this is the "root" database. If a user is added to this database, the user automatically inherits all database permissions. Certain server-side commands can also only be run from this database, such as listing all databases or shutting down the server.

  • local:This data will never be copied and can be used to store any collection limited to a single local server

  • config: When Mongo is used for sharding setup, the config database is used internally to save information about shards.


Document

The document is a key-value pair (i.e. BSON). MongoDB documents do not need to have the same fields, and the same fields do not need to be of the same data type. This is very different from relational databases and is also a very prominent feature of MongoDB.

A simple document example is as follows:

{"site":"www.php.cn", "name":"php中文网"}

The following table lists the terms corresponding to RDBMS and MongoDB:

##TableCollectionRowsDocumentColumnsFieldsTable UnionEmbedded documentPrimary keyPrimary key (MongoDB provides the key as _id)Database service and clientMysqld/Oraclemongodmysql/sqlplusmongo

It should be noted that:

  1. The key/value pairs in the document are ordered.

  2. The value in the document can not only be a string inside double quotes, but also several other data types (or even the entire embedded document).

  3. MongoDB is type and case sensitive.

  4. MongoDB documents cannot have duplicate keys.

  5. The key of the document is a string. With few exceptions, keys can use arbitrary UTF-8 characters.

Document key naming convention:

  • keys cannot contain \0 (null character). This character is used to indicate the end of the key.

  • . and $ have special meanings and can only be used under specific circumstances.

  • Keys starting with an underscore "_" are reserved (not strictly required).


Collection

A collection is a MongoDB document group, similar to a table in RDBMS (Relational Database Management System).

Collections exist in databases. Collections have no fixed structure, which means that you can insert data in different formats and types into the collection, but usually the data we insert into the collection will have a certain correlation.


For example, we can insert the following documents with different data structures into the collection:

{"site":"www.baidu.com"}
{"site":"www.google.com","name":"Google"}
{"site":"www.php.cn","name":"php中文网","num":5}

When the first document is inserted, the collection will be create.

Legal collection name

  • The collection name cannot be the empty string "".

  • The collection name cannot contain the \0 character (null character). This character represents the end of the collection name.

  • The collection name cannot start with "system.", which is a prefix reserved for system collections.

  • The collection name created by the user cannot contain reserved characters. Some drivers do support inclusion in collection names because some system-generated collections contain this character. Never use $ in the name unless you are accessing such a system-created collection.

The following examples:

db.col.findOne()

capped collections

Capped collections are fixed-size collections.

It has high performance and queue expiration features (expiration is in the order of insertion). It is somewhat similar to the "RRD" concept.

Capped collections are high-performance automatic maintenance of the insertion order of objects. It's great for functionality like logging Unlike standard collections, you must explicitly create a capped collection. Specify the size of a collection in bytes. The data storage space value of the collection is allocated in advance.


It should be noted that the specified storage size includes the header information of the database.


db.createCollection("mycoll", {capped:true, size:100000})
  • In a capped collection, you can add new objects.

  • Can be updated, however, the object does not increase storage space. If increased, the update will fail.

  • The database does not allow deletion. Use the drop() method to delete all rows in the collection.

  • Note: After deletion, you must explicitly recreate the collection.

  • In a 32bit machine, the maximum storage capacity of capped collection is 1e9 (1X109) bytes.


Metadata

Database information is stored in collections. They use the system namespace:

dbname.system.*

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

RDBMSMongoDB
DatabaseDatabase
Collection namespacesDescription
dbname.system.namespacesList all namespaces.
dbname.system.indexesList all indexes.
dbname.system.profileContains database profile information.
dbname.system.usersList all users who can access the database.
dbname.local.sourcesContains the server information and status of the replication peer (slave).

There are the following restrictions on modifying objects in the system collection.

Insert data in {{system.indexes}} to create an index. But otherwise the table information is immutable (the special drop index command will automatically update the relevant information).

{{system.users}} is modifiable. {{system.profile}} is removable.


MongoDB data types

The following table shows several commonly used data types in MongoDB.

Data TypeDescription
StringString. Commonly used data types for storing data. In MongoDB, UTF-8 encoded strings are legal.
IntegerInteger value. Used to store numerical values. Depending on the server you use, it can be either 32-bit or 64-bit.
BooleanBoolean value. Used to store boolean values ​​(true/false).
DoubleDouble precision floating point value. Used to store floating point values.
Min/Max keysCompares a value to the lowest and highest value of a BSON (binary JSON) element.
Arrays Used to store an array or list or multiple values ​​as a key.
TimestampTimestamp. Record the specific time when the document was modified or added.
Object is used for embedded documents.
Null is used to create null values.
SymbolSymbol. This data type is basically identical to the string type, except that it is typically used in languages ​​that use special symbolic types.
DateDate time. 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 the year, month and day information.
Object IDObject ID. The ID used to create the document.
Binary DataBinary data. Used to store binary data.
CodeCode type. Used to store JavaScript code in documents.
Regular expressionRegular expression type. Used to store regular expressions.

php.cn