MongoDB Beginner Tutorial

A free, open source, multiplatform document-oriented database software, written in the C ++ language.


MongoDB Beginner Tutorial

MongoDB is a free, open source, multiplatform document-oriented database software, written in the C++ language.

Classified as a database program NoSQL (generic term that represents non-relational databases, that is, it is not based on the principle that all data are stored in tables).

MongoDB uses documents similar to JSON with schematics.

It is developed by MongoDB Inc. and published under a combination of the GNU Affero General Public License and Apache License.

Data model

As the data is stored in MongoDB (JSON style), so it is a non-relational database (unlike MySQL, Oracle, PostgreSQL, SQLite, …).

Relational Model: Relational Model

MongoDB Model (NOT Relational): NOT Relational JSON

Terminologies in MongoDB

Database

The database is a physical container for collections.

Collection

Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table.

Document

A document is a set of key-value pairs. The documents have a dynamic layout.

Comparison with names used in SQL

RDBMS MongoDB
Database Database
Table Collection
Line Document
Column Field
Table join Embedded documents
Primary Key Primary Key (standard key _id provided by mongodb himself)
mysqld/oracle mongod
mysql/sqlplus Mongo

Sample document

The following example shows the structure of a blog document, which is simply a pair of key values ​​separated by commas.

{
   _id: ObjectId(7df78ad8902c)
   title: 'MongoDB overview',
   description: 'MongoDB, a NoSQL database',
   by: 'Marcos Oliveira',
   url: 'https://en.terminalroot.com.br',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100,
   comments: [
      {
         user:'user1',
         message: 'My first comment',
         dateCreated: new Date(2011,1,20,2,15),
         like: 0
      },
      {
         user:'user2',
         message: 'My second comment',
         dateCreated: new Date(2011,1,25,7,45),
         like: 5
      }
   ]
}

Advantages of MongoDB

Several large sites, mainly WebCommerces use MongoDB, as it generates a lot of work and server processing when creating a variety of data from a single product.

For example, in a notebook there are several descriptive data: brand, model, series, description, color, … and that for those who program databases know the “headache” that is to create these relationships in SQL. But with MongoDB this is very simple.

Among several areas such as:

  • Big data
  • Mobile and social infrastructure
  • User data management
  • DataHub They use MongoDB.

Installation

First of all, you need to have the XFS file system enabled in Kernel, as MongoDB uses it together with the GNU C Library, better known as glibc:

This will only be necessary if you use Gentoo

su
cd /usr/src/linux
make menuconfig

Enable according to these images:

File System Kernel Linux XFS Kernel Linux

Then rebuild and restart the computer:

This will only be necessary if you use Gentoo

make && make modules_install && make install
grub-mkconfig -o /boot/grub/grub.cfg
reboot

In Gentoo just run the command (or without sudo with the user root, su -c "emerges dev-db/mongodb"):

Use --ask or just -a as a parameter, and if you want not to add to * world * use --oneshot or simply -1, example: sudo emerges -a1 dev-db/mongodb

sudo emerges dev-db/mongodb

For other Linux distributions

sudo apt install mongodb # Debian, Ubuntu, Mint,...
sudo pacman -S mongodb # Arch Linux, Manjaro,...
sudo yum install mongodb # Red Hat, CentOS,...
sudo dnf install mongodb # Fedora
sudo zypper install mongodb # OpenSUSE
# ...

After installing, you need to create a directory at the root of your system for MongoDB to create the directory for databases:

sudo mkdir -p /data/db

Now check if there is already a mongodb group created with the command:

cat /etc/group | cut -d: -f1 | grep mongodb

If the output is: mongodb, then everything is fine, if not, you will need to create this group with the command: sudo groupadd mongodb

Now add your user to that group:

After adding, it will be necessary to log out and log back into the system for the changes to take effect.

sudo usermod -aG mongodb $USER

Settings

The MongoDB configuration file can be found at: cat /etc/mongodb.conf and it contains the following information:

‘Commented’ lines (starting with # are ignored)

storage:
    dbPath: "/data/db"

systemLog:
    destination: file
    path: "/var/log/mongodb/mongodb.log"
    quiet: true
    logAppend: true

net:
    port: 27017
    bindIp: 127.0.0.1

About the settings:

  • dbPath: "/data/db" - The MongoDB path, if yours is with /var/lib/mongodb change to this;
  • path: "/var/log/mongodb/mongodb.log" - Where the logs are kept;
  • port: 27017 - The default port, that is, you do not need to start MongoDB with the command: mongo --port 27017 if this line is properly configured and “uncommented”.
  • bindIp: 127.0.0.1 - Execution address, that is, the loopback, if you want to change to a specific address, use this line.

To avoid permission problems, I recommend that you delete everything that might exist inside the directory: /var/lib/mongodb

sudo rm /var/lib/mongodb/*

After that, it is necessary to start the daemon, in this case for OpenRC:

If you use SystemD, see the equivalent command here: https://wiki.gentoo.org/wiki/OpenRC_to_systemd_Cheatsheet

sudo rc-service mongodb start

If you want MongoDB to start automatically whenever you start your system, run:

sudo rc-update add mongodb default

If you want to check if the service is already running, use one of these commands: rc-service mongodb status.

Example: OpenRC MongoDB

After properly configured, just enter MongoDB via shell:

mongo

To exit MongoDB, simply run the command: exit.

Creating an administrator user

In the mongo shell, add a user with the userAdminAnyDatabase role in the admin database. Add additional functions as needed for this user. For example, the following creates the user username in the admin database with the userAdminAnyDatabase function and the readWriteAnyDatabase function.

As of version 4.2 of the mongo shell, it is possible to use the passwordPrompt() method in conjunction with various methods/authentication commands/user management to request the password, instead of specifying the password directly in the method call/command. However, you can still specify the password directly as you would with previous versions of the mongo shell.

use admin
db.createUser (
  {
    user: "userName",
    pwd: passwordPrompt(), // or pwd: "abc123", or even a blank password
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ] // full privileges
  }
)

If you want to copy and paste the code (Shift + Control + V, to paste in the terminal) with the necessary changes made, example output:

Successfully added user: {
	"user" : "marcos",
	"roles" : [
		{
			"role" : "userAdminAnyDatabase",
			"db" : "admin"
		},
		"readWriteAnyDatabase"
	]
}

Exit the mongo shell exit. Now to log in the parameters are similar to that of MySQL:

mongo -u username -p
# MongoDB shell version v4.2.2
# Enter password: [TYPE_YOUR_PASSWORD]

Or with more details: mongo --port 27017 --authenticationDatabase "admin" -u "userName" -p

[Optional] - Create additional users if needed

Note that it will only have specific read and/or readWrite permissions on specific banks as well: test and reporting

use test
db.createUser (
  {
    user: "normaluser",
    pwd: passwordPrompt(), // or cleartext password
    roles: [{role: "readWrite", db: "test"},
             {role: "read", db: "reporting"}]
  }
)

Then just log in with that user: mongo --port 27017 -u "normalUser" --authenticationDatabase "test" -p.

The documentation has details for general situations, if you want to take a look documentation.

Using MongoDB (Commands)

  • Databases (databases)
    • show dbs - Lists all databases, the alias of this command is show databases;
    • use [database-name] - Select a database, eg: use admin;
    • db - Check which database is currently in use;
    • use terminalroot - Creates a database, but only effectively exists when you create a collection and insert some data into it, if it is not available when you list the banks, it will cease to exist;
    • db.dropDatabase() - Deletes a database, use after selecting use database-name What do you want;
  • Collections(tables)
    • show collections - Shows the collections;
    • createCollection() - Creates a collection, its prototype is createCollection("tableName", Options), example: db.createCollection ("mycolection").
    • db.COLLECTIONNAME.find().pretty() - Read all data in a collection, eg db.system.users.find().pretty (), read all data in the system.users, equivalent to SELECT * FROM table. This output will be formatted, if you want the data on a single line, use it without the .pretty() method: db.system.users.find();
    • db.COLLECTION.NAME.insert () - Insert data into a collection, eg: db.mycolection.insert ({"_id": 0, " site" : "Terminal Root" , "url" : "en.terminalroot.com.br", "content" : " About MongoDB"});
    • db.COLLECTION_NAME.update (QUERY_NAME, THE_UPDATE, Options) - Updates (UPDATE) data in a Document (field), eg: db.mycolection.update ({'content': 'About MongoDB'}, { $ set: {'content': 'MongoDB Definitive Tutorial'}}) , changes the document named content which has the value: About MongoDB by MongoDB Definitive Tutorial;
    • db.COLLECTION_NAME.drop() - Deletes a collection, eg: db. mycollection.drop(), deletes the collection mycolection.
  • help output as shown in the image below: help MongoDB

See the image below of some commands we quote: MongoDB Terminal Root command

For more commands see the comparison reference and if you already know SQL and want to translate the command to MongoDB use QueryMongo. 😀️

More command information

# Shell
mongo --help
mongo man

# Server
mongod --help
mongod man

# Data Dump Utility
mongodump --help
mongodump man

# Export Utility
mongoexport --help
man mongoexport

# GridFS Utility
mongofiles --help
man mongofiles

# Import Utility
mongoimport --help
mongoimport man

# Traffic capture and replay tool
mongoreplay --help
man mongoreplay

# Data restoration tool
mongorestore --help
mongorestore man

# Cluster Lookup Router
mongos --help
man monks

# Statistics utility
mongostat --help
mongostat man

# Activity Monitor
mongotop --help
mongotop man

Useful links

Thanks for reading!


mongodb mysql cpp


Share


YouTube channel

Subscribe


Marcos Oliveira

Marcos Oliveira

Software developer
https://github.com/terroo

Related articles