MongoDB Data Model

Source: Internet
Author: User
Tags local time

MongoDB Database Introduction
    • Characteristics

      • For collection Storage
      • Rich query Statements
      • Replication set mechanism
      • Support for file storage
      • Mode freedom
      • Multilevel index
      • Easy Horizontal Expansion
      • Wide cross-platform and Support languages
      • Pluggable Storage engines (3.0)
    • Applicable scenarios

      • Data caching
      • JSON-formatted data
      • The office stretched out like a sex scene
      • Weak transaction type Business

      MongoDB is more suitable for large data volume, high concurrency, weak transactions of the Internet applications, its built-in horizontal expansion mechanism provides millions of to 1 billion levels of data processing capabilities, can be very good to meet Web2.0 and mobile Internet applications data storage requirements.

Related Sites for MongoDB

Official Document: https://docs.mongodb.com/tutorials/

Chinese website: http://www.mongoing.com/

Google group:https://groups.google.com/forum/

MongoDB Concept Analysis TR class= "even" >
SQL terminology/Concepts MongoDB terminology/Concepts Explanation/description
database database database
table collection database Table/collection
row document data record Line/document
column Field data fields/fields
index index index
table joins embedded documents/reference table connection/(inline/reference)
primary key primary key primary key, MongoDB automatically _id field set as primary key

Through the example, you can more intuitively understand Mongo some of the concepts:

Database

Multiple documents make up a collection, and multiple collections make up a database. A MongoDB instance can host multiple databases, each with separate permissions, and on disk, different databases can be placed in different folders (with the DIRECTORYPERDB option at startup).

For better organization of data, in general, all data belonging to the same application (or the same business type) is placed in a database.

show dbscommand to display a list of all data.

? at [09/10/17][0:21:00] ? ?  mongoMongoDB shell version: 3.2.11connecting to: test> exitbye? at [09/10/17][0:21:04] ? ?  mongoMongoDB shell version: 3.2.11connecting to: test> show dbslocal  0.000GB

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

> dbtest

Run use db_name the command, switch the database, create it automatically when there is no database

The above instance command local is the database you want to link to.

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

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).
  • Database names are case-sensitive (it is recommended that database names all use lowercase)
  • Up to 64 bytes.
  • Do not have the same name as the database reserved by the system, including: admin, local, config, etc.

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 used for sharding settings, the database is used config internally to hold information about the Shard.
Related actions
Command Operation
db View Current Database
show dbs See how many databases are on the current port
use db_name Switch database, automatically created without database
db.dropDatabase() Deleting a database
Document

The document is the core concept of MongoDB, which is essentially a kind of JSON-bson-formatted data.
Bson is a JSON-like binary format data that can be understood to add some new data types based on JSON, including Yue, Int32, Int64, and so on.
Bson is composed of a set of group key-value pairs, which has the characteristics of lightness, ergodic and high efficiency. The ergodic nature is the main reason for MongoDB to store Bson as data.
Bson website Address: http://bsonspec.org/

{    fieldl:valuel,    field2:value2,    field3:value3,    ...    fieldN:valuen}

The following table lists RDBMS the MongoDB corresponding terms:

RDBMS MongoDB
Database Database
Form Collection
Yes Document
Column Field
Table Union Embed a document
Primary key Primary KEY ( MongoDB supplied with key _id)
Database Services Client
Mysqld/Oracle mysql/sqlplus
mongod mongo

It is important to note that:

  1. The key/value pairs in the document are ordered. MongoDB will try to keep the order of key-value pairs when the document is inserted
  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.
  6. The atomicity of write operations in MongoDB is restricted at the document level, and the preservation, modification, and deletion of documents are atomic operations.
  7. A single document cannot occupy more than 16MB of storage space

There are a few things to keep in mind about naming a document key:

  • _ID is the system-reserved keyword, which is the default primary key, which must be unique in the collection and cannot be changed
  • . (namespaces) and $ (operators) have special meanings that can only be used in a specific environment.
  • Keys that begin with the underscore "_" are reserved (not strictly required).
  • The key cannot contain either a/s or a null character, which is used to denote the end of a key
  • Keys are case-sensitive and cannot be duplicated for example: {foo:l,foo:l}
Inline document

A document can be a value of a key, such a document is called an inline document. Embedded documents make it more natural to organize data without storing it as a key-value pair in a flat structure.

For example, here is a document related to blog management

{    _id:<Objectldl>,     title:MongoDBDateModeln,     author:foo,     comments:[    {who:"John",comment:"Good"},     {who:"Joe",comment:"ExceUent"}    ]}

The above document can be split as follows:

is split into reference documents.

Embedded document Features

    • Sub-documents are relatively young, can guarantee atomicity, at the same time with high-speed query;
    • More than a few subdocuments can affect query and update speed, but also bring data redundancy
Collection

Put a set of related documents together to form a collection, if a MongoDB document is likened to a row in a relational database, then a collection is equivalent to a table.

The collection of MongoDB is free of patterns, and a collection of documents can be of a variety.

For example, the following two documents can appear in the same collection.

{"x":1}{"x":1,"y":2}{"x":1,"y":2,"z":5}

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

MongoDB provides a collection of special features, such as Cappedcollection, System.indexes, system.namespaces, and so on.

Valid set name

    • The collection name cannot be an empty string "".
    • The collection name cannot contain a \0 character (a null character), which represents the end of the collection name.
    • The collection name cannot system. begin with, which is the 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. Unless you want to access the collection created by this system, never appear in the name $ (note: can contain.)

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.
Name space

Add the database name to the name of the collection, in the middle of the connection with a dot, to get the fully qualified name of the collection, which is the namespace, for example: namespace Parent.sub.

Note that the point number can also appear in the collection name, for example: Parent.subling0,parent.subling2 can treat the SUBLING0 and subling2 collections as subsets of the parent collection.
Using subcollections allows us to better organize the data and make the structure of the data clearer.

Meta data

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

dbname.system.*

Namespaces in the MongoDB database <dbname>.system.* are Special Collections (Collection) that contain a variety of system information, as follows:

Collection Namespaces Description
db.system.namespaces Lists all namespaces.
db.system.indexes Lists all indexes.
db.system.profile Contains database summary (profile) information.
db.system.users Lists all users who can access the database.
db.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.

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

{{system.users}}is modifiable. {{system.profile}}can be deleted.

MongoDB data type

Bson can be understood to add some new data types based on JSON, including date, positive-shell ij expression, further partitioning of numeric types, and so on.

Data Type Type number Data Type Type number
Double 1 Regular Expression 11
String 2 Javascript 13
Object 3 Symbol 14
Array 4 JavaScript (Scope) 15
BinaryData 5 32-bit integer 16
Object ID 7 Timestamp 17
Boolean 8 64-bit integer 18
Date 9 Min Key 255
Null 10 Max Key 127

You can use a type number to make a conditional query as follows:

db.collection.find({name:{$type:2}})
Basic data types
  • Null represents a null or nonexistent field for example: Db.collection.find ({nyn:null})

    • Boolean has two values of true or FALSE for example: {"Y": true}
  • Numeric types support 32-int, 64-int, and 64-double

    Note: JavaScript only supports 64-bit floating-point numbers

    For example:

    • {"Y": ten}-double
    • {"Y": Numberlnt (10)}-32
    • {"Y": Numberlong (10)}-64
    7 Documents:0 > db.demo.insert({y:10})WriteResult({ "nInserted" : 1 })8 Documents:1 > db.demo.find({y:{$type:1}}){ "_id" : ObjectId("5a7863305640374fb2cd5620"), "y" : 10 }9 Documents:1 > db.demo.insert({y:NumberInt(10)})WriteResult({ "nInserted" : 1 })10 Documents:2 > db.demo.find({y:{$type:16}}){ "_id" : ObjectId("5a78636d5640374fb2cd5621"), "y" : 10 }11 Documents:2 > db.demo.insert({y:NumberLong(10)})WriteResult({ "nInserted" : 1 })12 Documents:3 > db.demo.find({y:{$type:18}}){ "_id" : ObjectId("5a7863915640374fb2cd5622"), "y" : NumberLong(10) }
    • strings are encoded using UTF-8 for example: {"Y": "Hellomongodb"}
  • Binary data can hold strings of any byte, for example: pictures, videos, etc.

  • Regular expressions: Used primarily for queries, using regular expressions as a qualification

    For example:

    • {name:/foo/} Name field contains Foo's document
    • {name:/foo/i} Name field contains Foo's document, and is case insensitive
    • {name:/^foo/i} name field with Foo shipowner header, and case-insensitive
  • JavaScript code: A document can contain arbitrary JavaScript code

    For example: {"Func": Function () {}}

Date Dates
    • In MongoDB, a date type is a 64-bit integer that represents the number of milliseconds from Unixepoch
    • MongoDB converts to UTC time when storing time
    • Beijing time (CST) = UTC + 8 hours
    • Mongodbshell can use Newdate or isodate to create time objects, and when displayed, the shell sets the display Date object based on local time.
14 Documents:3 > var mydate0 = new Date()15 Documents:3 > var mydate9 = ISODate()16 Documents:3 > mydate0ISODate("2018-02-05T14:04:43.243Z")17 Documents:3 > mydate9ISODate("2018-02-05T14:04:57.715Z")18 Documents:3 > mydate9.toString()Mon Feb 05 2018 22:04:57 GMT+0800 (CST)
Timestamp
    • A timestamp type consists of two parts:

    • TIMESTMP is only used internally by the MongoDB database service to record the detailed time of the operation
    • The timestamp type is not related to the date type, and more date types are used for us
    • Correlation function: Timestamp ()
Objectld

OBJECTLD consists of 24 hexadecimal characters, each byte storing two hexadecimal digits, a total of 12 bytes of storage space

Each byte represents the following meanings:

The objectld generated in this way is still unique in the distribution.

related functions :

    • Objectld ()

      Used to obtain OBJECTLD

    • Gettimestamp ()

      Timestamp used to obtain the OBJECTLD

    • ValueOf ()

      The string representation used to get objectld

19 Documents:3 > x = ObjectId()ObjectId("5a7866e75640374fb2cd5623")20 Documents:3 > x.getTimestamp()ISODate("2018-02-05T14:15:03Z")21 Documents:3 > x.valueOf()5a7866e75640374fb2cd5623
Array
    • An array is a set of values, expressed in square brackets, that can be used as an ordered object (list, stack, Team Evil | J), can also act as an unordered object (such as a collection)

    • An array can contain elements of different data types (strings, floating-point numbers, documents, and so on)

      For example: [3.14, "Hello", [l2,3],{"Key": "MongoDB"}]

      A number of specific operators are provided for the array MongoDB, for example:,,, $push $pop $pull $slice , $addToSet etc.

    • MongoDB can automatically establish an Multikey index for an array element

MongoDB Data Model

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.