MongoDB Concept Parsing Tutorial | MongoDB Concept Analysis

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 / concept MongoDB terminology / concept explain
Database Database database
Table Collection Database table/collection
Row Document Data record line/document
Column Field Data field/domain
Index Index index
Table joins Table connection, MongoDB does not support
Primary key Primary key Primary 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:

RDBMS MongoDB
database database
form set
Row Document
Column Field
Table union Embedded document
Primary key Primary key (MongoDB provides the key _id )
Database service and client
Mysqld/Oracle Mongod
Mysql/sqlplus Mongo

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 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 have access to the database.
Dbname.local.sources Contains 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 data description
String String. The type of data that is commonly used to store data. In MongoDB, UTF-8 encoded strings are legal.
Integer Integer value. Used to store values. Depending on the server you are using, it can be divided into 32 or 64 bits.
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 Compare a value to the lowest and highest values of the BSON (binary JSON) element.
Array Used to store an array or list or multiple values as a single key.
Timestamp Timestamp. Record the exact time the document was modified or added.
Object Used for embedded documents.
Null Used to create null values.
Symbol symbol. 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.
Date Date 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 ID Object ID. The ID used to create the 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 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

1 thought on “MongoDB Concept Parsing Tutorial | MongoDB Concept Analysis”

  1. Great goods from you, man. I’ve take into account your stuff prior to
    and you’re just too great. I actually like what you havbe obtained here, reallly like what you are stating aand the
    best way through which you are saying it. Youu are making
    it entertaining and you continue to take care of to stay it sensible.

    I cant wait to learn far more from you. That is really a terrific website.

    Reply

Leave a Comment