What is a Collection in MongoDB?
September 14, 2018
What is Hadoop?
September 14, 2018

How to use MongoDB

How to Install and Use MongoDB?

MongoDB is trusted and used by many big names across different industries and allows them to intelligently put their data where they want, including AWS, Google Cloud Platform and Azure. The cross-platform and open-source NoSQL database makes it easier for users to get started and accomplish more in less time. MongoDB also comes with detailed documentation and easy-to-follow instructions. The installation and setup instructions have been summarized in this post to make it easier for users to get started.

Installing and Starting MongoDB

MongoDB supports x86_64, ARM64, PPC64LE (Enterprise Edition) and S390X and is available in two editions i.e. community and enterprise. The community version is the open-source edition of the DB, while the Enterprise version includes additional functionalities. Installation steps vary according to the edition being installed, while this post focuses on the community edition.

Microsoft Windows Installation and Startup

MongoDB requires at least Windows 7 or Server 2008 R2 and X86_64 architecture. It’s recommended to enable the ‘show file extensions’ option in Windows so you know the exact file type you are dealing with. It’s also recommended to ensure that the latest security fixes and updates are installed.

Installing MongoDB on Windows is fairly straight forward and easy as the .msi file includes everything you need, while you also don’t have to worry about the dependencies. The Wizard-based installer updates any previously installed version automatically (in the same release series). You can also install the DB using Windows Command Interpreter (cmd.exe) using the following command:

msiexec.exe /l*v mdbinstall.log  /qb /i mongodb_filename.msi

To start MongoDB you need a data directory to store all your data and to create these directories you can use:

md \data\db

Or

md “\data\db” “\data\log” (If you want to create more than one directory path using a single command)

The following command starts MongoDB by invoking mongod.exe

“C:\Program Files\MongoDB\Server\4.0\bin\mongod.exe” –dbpath=”c:\data\db”

“[initandlisten]” waiting for connections” means the database server is running correctly.

You might encounter a Security Alert if the firewall is blocking the DB so you’d have to allow MongoDB to access communications and networks.

Finally, use “C:\Program Files\MongoDB\Server\4.0\bin\mongo.exe” to connect to MongoDB

You can also start MongoDB as a Windows service using:

net start MongoDB

[initandlisten] to verify that the DB has started successfully

and “C:\Program Files\MongoDB\Server\4.0\bin\mongo.exe” to connect to the DB

“net stop MongoDB” and “sc.exe delete MongoDB” can be used to stop and remove MondoDB as a Windows service

macOS Installation and Startup

MongoDB requires MacOS 10.11 or above and Intel x86_64 architecture to work on the platform. To manually install the DB download the .tar.gz tarball and extract the files using the following command:

tar -zxvf file_name.tgz (binaries [bin/] must be located in the directory listed in the PATH environment variable)

You can either copy these binaries into a directory that is listed in the PATH variable and create symbolic links to each or modify user’s PATH variable to include the directory.

MongoDB can also be installed on MacOS with Homebrew that installs binary packages (requires initial setup and configuration)

Invoke “brew update” in a system shell before proceeding to installation of MongoDB

The following commands can be used to install MongoDB using Homebrew (from system shell)

brew install mongodb

brew install mongodb –devel (latest development release)

You need to create the data directory before running MongoDB for the first time on MacOS using the following command (the user should have read and write permissions for the directories):

mkdir -p /data/db

Mongod

You can also specify path for mongod if it does not include location of the binary using

<path to the binary>/mongod

“mongod –dbpath < data directory path>” specifies the path of the data directory in case you are not using the default directory

Use “[initandlisten]” to verify that the DB has started successfully

You can start a mongo shell and begin using the DB using

mongo –host local_host_address:port

Press Ctrl+C to stop the MongoDB instance in the terminal

Linux Installation

Individual packages for some of the most popular and major Linux distribution are available, making installation easier (.rpm packages for Red Hat, SUSE and Amazon and .deb for Ubuntu and Debian). MongoDB also works with the community to provide packages for other Linux distributions and BSD systems such as Arch Linux, Fedora, FreeBSD, openSUSE and Gentoo.

Creating a Table in MongoDB

You need to have a db and collection in place before creating a table. A database stores all the collections, while a collection stores all the documents, which contain relevant field_names (such as Customer name) and field_values (the actual names).

The ‘use’ command creates a database and switches to the database automatically e.g.

use Customer

To easiest method to create a collection is inserting a record, which is essentially a document containing field_names and field_values e.g.

db.Customer.insert

(

                          {

                                         “Customerid” : 1,

                                         “Customername” : “David”

                          }

           )

 

Retrieving Data through MongoDB

You can read data from MongoDB using a variety of clients, including the Mongo Shell, Compass, Python, NODE.JS, JAVA (SYNC), MOTOR and C#.

Windows

Verify that MongoDB instance is running before reading data using:

tasklist /FI “IMAGENAME eq mongod.exe”

MongoDB is running if you see the PID, session name and other information.

Connect to the DB instance using

mongo.exe mongodb://$[hostlist]/$[database]?authSource=$[authSource] –username $[username]

Switch to the database for example the database “sample”

use sample

Enter the following command to retrieve all documents stored in the example collection (inventory), the shell returns up to 20 results

myCursor = db.inventory.find( {} )

MacOS and Linux

The procedure for retrieving data is the same on MacOS and Linux, but commands differ when running a MongoDB instance as follows (you also need to remove ‘.exe’ when connecting to a DB instance) :

ps -e | grep ‘mongod’

Conclusion

MongoDB is one if the easiest NonSQL databases to learn and setup and stores data in JSON-style documents. This allows indexing on virtually any attribute and easy replication. The document structure is in-line with how developers construct objects and classes, which significantly reduces the learning curve and offers a clear structure.

Although MongoDB is easy to learn, it’s not so easy to master and requires some time and effort. MongoDB University is a great place to master the database and offers free courses as well as private training. Study guides are also available, while the MongoDB Developer Exam or the DBA exam ensures that developers have the skills and knowledge needed to compete in the ever-changing and challenging IT industry.

Leave a Reply

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