MongoDB Concept Parsing Tutorial | MongoDB Concept Analysis

MongoDB Tutorials

MongoDB Concept Parsing Tutorial from Coding compiler. Here you will learn MongoDB concept analysis like documents, collections, and databases. Learn Now.!

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 take a look at them.

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

SQL terminology / conceptMongoDB terminology / conceptexplain
DatabaseDatabasedatabase
TableCollectionDatabase table/collection
RowDocumentData record line/document
ColumnFieldData field/domain
IndexIndexindex
Table joinsTable connection, MongoDB does not support
Primary keyPrimary keyPrimary key, MongoDB automatically sets the _id field as the primary key

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

Related MongoDB Tutorials

What is MongoDB Tutorial For Beginners
MongoDB Basics Tutorial
MongoDB Update Tutorial
MongoDB Query Tutorial
MongoDB Data Modelling Tutorial
MongoDB Scenarios
MongoDB Aggregation Tutorial
MongoDB Performance And Tools

Database

Multiple databases can be created in one MongoDB.

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 collections and permissions, and different databases are placed in different files.

The “show dbs” command displays a list of all the 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.

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

  • Cannot be an empty string (“”).
  • Must not contain ‘ ‘ (space), ., $, /, \, and \0 (null characters).
  • It should be all lowercase.
  • Up to 64 bytes.

Some database names are reserved, and you can directly access these special-purpose databases.

  • Admin : From a privilege perspective, this is the “root” database. If a user is added 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 will never be copied and can be used to store any collection limited to a local single server.
  • Config : When Mongo is used for sharding setup, the config database is used internally to hold information about the shard.

Document

A document is a set of key-value pairs (ie BSON). MongoDB’s documentation does not need to set the same fields, and the same fields do not need the same data type, which is very different from relational databases, and is also a very prominent feature of MongoDB.

An example of a simple document is as follows:

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

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

RDBMSMongoDB
databasedatabase
formset
RowDocument
ColumnField
Table unionEmbedded document
Primary keyPrimary key (MongoDB provides the key _id )
Database service and client
Mysqld/OracleMongod
Mysql/sqlplusMongo

have to be aware of is:

  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’s documentation cannot have duplicate keys.
  5. The key of the document is a string. With a few exceptions, the key can use any UTF-8 character.

Document key naming convention:

  • The key cannot contain \0 (null character). This character is used to indicate the end of the key.
  • And $ have special meaning and can only be used in certain circumstances.
  • Keys beginning with an underscore “_” are reserved (not strictly required).

Set

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

Collections exist in the database, and collections have no fixed structure, which means that you can insert data of different formats and types into the collection, but usually the data we insert into the collection will have some relevance.

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

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

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

Legal collection name

  • The collection name cannot be an empty string “”.
  • The collection name cannot contain a \0 character (a null character), which indicates the end of the collection name.
  • Collection names cannot begin with “system.”, which is a prefix reserved for system collections.
  • User-created collection names cannot contain reserved characters. Some drivers do support inclusion in collection names because some system-generated collections contain this character. Do not appear in the name unless you want to access the collection created by this system.

The following example:

Db.col.findOne()

Capped collections

Capped collections are fixed-size collections.

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

Capped collections are the insertion order of high-performance automatic maintenance objects. It’s great for logging-like features unlike standard collections. You must explicitly create a capped collection that specifies the size of a collection in bytes. The data storage space value of the collection is allocated in advance.

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

db.createCollection("mycoll", {capped:true, size:100000})
  • In the capped collection, you can add new objects.
  • Can be updated, however, the object does not increase storage space. If it increases, the update will fail.
  • The database does not allow deletion. Use the drop() method to delete all rows of the collection.
  • Note: After deleting, you must explicitly recreate this collection.
  • In a 32-bit machine, the capped collection stores a maximum of 1e9 (1X10 9 ) bytes.

Metadata

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 collection containing a variety of system information, as follows:

Collection namespacedescription
Dbname.system.namespacesList all namespaces.
Dbname.system.indexesList all indexes.
Dbname.system.profileContains database profile information.
Dbname.system.usersList all users who have access to the database.
Dbname.local.sourcesContains server information and status of the replicated slave.

There are restrictions on 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 will automatically update the relevant information).

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


MongoDB data type

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

type of datadescription
StringString. The type of data that is commonly used to store data. In MongoDB, UTF-8 encoded strings are legal.
IntegerInteger value. Used to store values. Depending on the server you are using, it can be divided into 32 or 64 bits.
BooleanBoolean value. Used to store Boolean values (true/false).
DoubleDouble precision floating point value. Used to store floating point values.
Min/Max keysCompare a value to the lowest and highest values of the BSON (binary JSON) element.
ArrayUsed to store an array or list or multiple values as a single key.
TimestampTimestamp. Record the exact time the document was modified or added.
ObjectUsed for embedded documents.
NullUsed to create null values.
Symbolsymbol. This data type is basically equivalent to a string type, but the difference is that it is generally used for languages that use special symbol types.
DateDate time. Store 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 a document.
Regular expressionRegular expression type. Used to store regular expressions.

The following are some of the important data types.

ObjectId

ObjectId is similar to a unique primary key and can be generated and sorted very quickly, containing 12 bytes, meaning:

  • The first 4 bytes represent the creation of a unix timestamp, UTC time in Greenwich Mean Time, 8 hours later than Beijing time
  • The next 3 bytes are the machine identification code.
  • The next two bytes are composed of the process id to form the PID
  • The last three bytes are random numbers

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

Since the created timestamp is saved in the ObjectId, you don’t need to save the timestamp field for your document. You can get the creation time of the document by using the getTimestamp function:

> var newObject = ObjectId()
> newObject.getTimestamp()
ISODate("2017-11-25T07:21:10Z")

Convert ObjectId to a string

> newObject.str
5a1919e63df83ce79df8b38f

String

BSON strings are all UTF-8 encoded.

Timestamp

BSON has a special timestamp type for internal MongoDB use that is not relevant for normal date types. The timestamp value is a 64-bit value. among them:

  • The first 32 bits are a time_t value (seconds difference from the Unix new era)
  • The last 32 bits are an increment of operation in a second

In a single MongoDB 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 primarily used internally by MongoDB. In most cases of application development, you can use the BSON date type.

date

Indicates the number of milliseconds currently in the Unix New Era (January 1, 1970). Date types are signed, and negative numbers indicate dates before 1970.

> var mydate1 = new Date() //Greenwich Mean Time
> mydate1
ISODate("2018-03-04T14:58:51.233Z")
> typeof mydate1
Object
> var mydate2 = ISODate() //Greenwich Mean Time
> mydate2
ISODate("2018-03-04T15:00:45.479Z")
> typeof mydate2
Object

The time created in this way is the date type, and you can use the method of the Date type in JS.

Returns a string of 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) 

Related MongoDB Tutorials For Beginners

What is MongoDB Tutorial For Beginners

MongoDB Basics Tutorial

MongoDB Update Tutorial

MongoDB Query Tutorial

MongoDB Data Modelling Tutorial

MongoDB Scenarios

MongoDB Aggregation Tutorial

MongoDB Performance and Tools

What is NoSQL

Leave a Reply

Your email address will not be published. Required fields are marked *