MongoDB Concept Analysis

Source: Internet
Author: User
Tags reserved

MongodbConceptual Analysis

No matter what database we learn, we should learn the basic concepts, the basic concept in MongoDB is a document, a collection, a database, we introduce each one.

The following table will help you understand some of the concepts in MONGO more easily:

SQL Terminology/Concepts MongoDB Terminology/Concepts Explanation/Description
Database Database Database
Table Collection Database Tables/Collections
Row Document Data record lines/documents
Column Field Data fields/Fields
Index Index Index
Table joins Table connection, MongoDB not supported
Primary key Primary key Primary key, MongoDB automatically sets the _id field as the primary key

With examples, we also have a more intuitive understanding of some of the concepts in MONGO:

Database

Multiple databases can be built in a mongodb.

The default database for MongoDB is "DB", and the database is stored in the data directory.

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

the show DBS command can display a list of all data.

./MONGOMongoDB Shell version:3.0.  6connecting to: Test> show dbslocal0.078GB0.078GB>  

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

./MONGOMongoDB Shell version:3.0.  6connecting to: test> dbtest>        

You can connect to a specified database by running the "use" command.

> Uselocallocal> dblocal>      

In the example command above, "Local" is the database you want to link to.

In the next section we will explain in detail the use of commands in MongoDB.

The database is also identified by name. The database name can be any UTF-8 string that meets the following criteria.

    • Cannot be an empty string ("").
    • Must not contain a ' (space) 、.、 $,/, \, and (null characters).
    • should be all lowercase.
    • Up to 64 bytes.

Some database names are reserved and can be accessed directly from these databases with special effects.

    • admin: From a permission point of view, this is the "root" database. If you add a user to this database, the user automatically inherits permissions from 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 copied and can be used to store any collection that is limited to a local single server
    • config: When MONGO is used for sharding settings, the Config database is used internally to hold information about the Shard.
Document

A document is a set of key-value (Key-value) pairs (that is, Bson). MongoDB documents do not need to set the same field, and the same field does not require the same data type, which is very different from the relational database, is also a very prominent MongoDB features.

An example of a simple document is as follows:

{"site":"www.runoob.com","name":"rookie Tutorial"}       

The following table lists the terms that the RDBMS corresponds to MongoDB:

RDBMS MongoDB
Database Database
Form Collection
Yes Document
Column Field
Table Union Embed a document
Primary key Primary KEY (MongoDB provides key for _id)
Database Services and clients
Mysqld/oracle Mongod
Mysql/sqlplus Mongo

It is important to note that:

    1. The key/value pairs in the document are ordered.
    2. The values in the document can be not only strings in double quotes, but also several other data types (even the entire embedded document).
    3. MongoDB distinguishes between type and case.
    4. MongoDB documents cannot have duplicate keys.
    5. The key of the document is a string. In addition to a few exceptions, keys can use any UTF-8 character.

Document key naming specification:

    • The key cannot contain a/s (null character). This character is used to denote the end of a key.
    • . and $ have special meaning and can only be used in certain circumstances.
    • Keys that begin with the underscore "_" are reserved (not strictly required).
Collection

A collection is a MongoDB document group, similar to a table in an RDBMS (relational database management system: Relational databases Management systems).

The collection exists in the database, the collection does not have a fixed structure, which means that you can insert data in different formats and types on the collection, but usually we have some relevance to the data that we insert into the collection.

For example, we can insert a document of the following different data structures into the collection:

{"site":"www.baidu.com"}{"site":"www.google.com","name":" Google "}{" site ":" www.runoob.com "," name ":" rookie Tutorial "," num " :5}                 

When the first document is inserted, the collection is created.

Valid set name
    • The collection name cannot be an empty string "".
    • The collection name cannot contain the \ s character (null character), which represents the end of the collection name.
    • The collection name cannot be "system." Begins with a prefix reserved for the system collection.
    • User-created collection names cannot contain reserved characters. Some drivers do support inclusion in the collection name, because some system-generated collections contain that character. Never show $ in a name unless you want to access a collection created by this system.

The following example:

DB.  Col.  FindOne()    
Capped collections

Capped collections is a fixed-size collection.

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

The Capped collections is a high-performance automatic maintenance object Insertion Order. It is very suitable for similar logging functions and the standard collection differs, you must explicitly create a capped collection, specifying the size of a collection, in bytes. Collection data storage space values are allocated in advance.

Note that the specified storage size contains the header information for the database.

DB.  CreateCollection("Mycoll",{capped:true, size:100000}) 
    • In capped collection, you can add new objects.
    • Can be updated, however, objects do not increase storage space. If it increases, the update will fail.
    • The database is not allowed to be deleted. Use the drop () method to delete all collection rows.
    • Note: After deletion, you must explicitly recreate this collection.
    • In a 32bit machine, the capped collection has a maximum storage of 1e9 (1x109) bytes.
Meta data

The information for the database is stored in the collection. They use the system's namespace:

dbname.  System. *  

In the MongoDB database, the namespace <dbname>.system.* is a special set (Collection) that contains a variety of system information, as follows:

Collection Namespaces Description
Dbname.system.namespaces Lists all namespaces.
Dbname.system.indexes Lists all indexes.
Dbname.system.profile Contains database summary (profile) information.
Dbname.system.users Lists all users who can access the database.
Dbname.local.sources Contains server information and status for the replication peer-to-peer (slave).

The following restrictions apply to modifying objects in a System collection.

You can create an index by inserting data in {{system.indexes}}. But otherwise the table information is immutable (the Special Drop INDEX command automatically updates the information).

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

MongoDB data type

The following table is a few of the data types commonly used in MongoDB.

Data Type Description
String String. Data types commonly used to store data. In MongoDB, the UTF-8 encoded string is legal.
Integer Integer value. Used to store numeric values. Depending on the server you are using, it can be divided into 32-bit or 64-bit.
Boolean Boolean value. Used to store Boolean values (True/false).
Double Double-precision floating-point value. Used to store floating-point values.
Min/max keys Compares a value to the lowest and highest value of a BSON (binary JSON) element.
Array Used to store an array or list or multiple values as a single key.
Timestamp Time stamp. Record when the document was modified or added.
Object Used for inline documents.
Null Used to create a null value.
Symbol Symbol. The data type is basically the same as the string type, but unlike it, it is typically used in languages with special symbol types.
Date Date time. Use the UNIX time format to store the current date or time. You can specify your own datetime: Create a Date object and pass in the month-date information.
Object ID The object ID. The ID used to create the document.
Binary Data Binary data. Used to store binary data.
Code The code type. Used to store JavaScript code in a document.
Regular expression The regular expression type. Used to store regular expressions.

The following are some important data types.

ObjectId

ObjectId similar to a unique primary key, can be quickly generated and sorted, including the bytes, meaning:

    • The first 4 bytes represent the creation of a Unix timestamp, UTC Time of GMT, 8 hours later than Beijing time
    • The next 3 bytes are the machine identification code
    • The immediate two bytes are composed of the process ID of the PID
    • The last three bytes are random numbers

The document stored in MongoDB must have a _id key. The value of this key can be any type, default is a ObjectId object

Since the created timestamp is saved in ObjectId, you do not need to save the timestamp field for your document, and you can get the document creation time by using the Gettimestamp function:

>var=ObjectId()> newObject.  Gettimestamp()isodate("2017-11-25t07:21:10z")      

ObjectId Convert to String

> newObject.  Str5a1919e63df83ce79df8b38f   
String

BSON strings are UTF-8 encoded.

Time stamp

BSON has a special timestamp type that is used for MongoDB internal use and is not related to normal date types. The timestamp value is a 64-bit value. which

    • The first 32 bits are a time_t value (the number of seconds that differs from the UNIX ERA)
    • The last 32 bits are an increment of the operation in a second序数

In a single Mongod instance, the timestamp value is usually unique.

In the replication set, Oplog has a TS field. The value in this field uses the Bson timestamp to indicate the operation time.

The BSON timestamp type is used primarily for MongoDB internal use. In most cases of application development, you can use the BSON date type.

Date

Represents the current number of milliseconds from the new Era of Unix (January 1, 1970). The date type is signed and the negative number represents the date before 1970.

> var  mydate1 = new date ()  //GMT > Mydate1isodate ( " 2018-03-04t14:58:51.233z ") >typeof Mydate1object        
>var=isodate()//GMT > mydate2isodate("2018-03-04t15:0 0:45.479z ")>typeof mydate2object        

This creates a date type, and you can use the method of the date type in JS.

Returns a string of a time type:

> Var Mydate1str = Mydate1. () > Mydate1str sun mar 04  2018 14: 58:51 Gmt+ 0000  (utc > typeof Mydate1str string               

Or

>Date()SunMar2018: 0000 GMT + (UTC)                
This article from https://www.runoob.com/mongodb/mongodb-databases-documents-collections.html

MongoDB Concept Analysis

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.