MongoDB Basic: How to connect to MongoDB

In this article, I am covering MongoDB basic for a beginner. When I started discovering MongoDB, I handled many small issues which I am going to discuss with you guys in this article as it’s not available on the MongoDB website. I have run all the below given examples on the windows machine.

MongoDB Short Intro

MongoDB is document database, in other words its non relational database. In MongoDB, JSON is used to query on the database which is human and machine-readable standard. MongoDB engine is based on BSON platform.

MongoDB natively support scaling out, so the application developer doesn’t need to worried about the database deployment model.

MongoDB design to support Agile development practices.

Install MongoDB on the Local Machine.

To install MongoDB on your local Windows machine, go to the MongoDB website. Under the download section, you will find the community server MongoDB MSI file. Click the file to download exe. Note this build is for 64 bit Windows machine.

Open the downloaded exe and install it.

mongodb screen1

 

How to run Local MongoDB Instance

When you installed MongoDB on your local Windows machine, you will find your MongoDB file on the path similar like “C:\Program Files\MongoDB\Server\3.4\bin\” and your folder view will look like as below. Here “server\3.4\” means I am using 3.4 version of MongoDB. In your case it may be different.

 

Now before starting the MongoDB server, we need to create folder on “C:\” drive like “C:\data\db” this will be location which Mongodb server will use to store the database files. You can change the default location using configuration setting.

Now open the command prompt and go to the MongoDB directory folder bin.

cd C:\Program Files\MongoDB\Server\3.4\bin\

To start local MongoDB server, use command Mongod on the command prompt.

C:\Program Files\MongoDB\Server\3.4\bin>mongod

This will start your local MongoDB server, your command prompt will look like the below screen.

mongod command server

If you got a similar screen like above without any error then your local MongoDB server is started. Don’t close this window. Open another console window to connect this database server as below.

How to Connect Local MongoDB Server.

To connect to local MongoDB, open the command prompt new window and type

CD C:\Program Files\MongoDB\Server\3.4\bin\

Now  to connect MongoDB, type mongo on command prompt.

Your command prompt will look like as below.

If you got the similar window message on your local machine, then congrats you are successfully connected to your local MongoDB server.

Check console message

connecting to: mongodb://127.0.0.1:27017

Here “mongodb://127.0.0.1:27017” is your local mongodb host address and don’t surprise because if it didn’t ask for user authentication. By default MongoDB server authentication is off.

To confirm you are connected on your own local server, which you just started, check the other command prompt window where you started the MongoDB server. You will find the below lines at the end of the console window.

server console connection

As last two lines say #1 connection open and connection accepted from the IP 127.0.0.1 which is your other console window connection to your local database server.

Test your MongoDB Server

Once you have connected to your local MongoDB server. To check the database, run the below command.
show dbs

If you want to create a new database, type “use <your databasename>”. I will create a new database name “blog” my command will be

use blog

This command will create a new temporary database blog. Now when you will add your first collection in this database, it will create this database permanently on your local database server.
So lets add the first collection to the database blog using the below MongoDB command to create a new collection.

 db.bloguser.insert({"name":"user1"})

Now we created a new collection with name “bloguser” in the “blog” database with “name” as key name and one value as “user1”.
Now if you run MongoDB command.

show collections

You will see “bloguser” collection.
Now to see the data in the collection if you run the MongoDB command

db.bloguser.findOne()

You will see the data which you added with “_id” field, here “_id” is MongoDB added unique key to your data.

mongodh show collection

How to Enable MongoDB Authentication

Till now we have learned how to Install MongoDB, how to start MongoDB server and how to connect to the server. Also we learned how to create a database, add a collection and check the records in the collections. While doing all these operations, we never used the userid password to connect the local instance of MongoDB.

When we started MongoDB server, we just executed command “Mongod”. “Mongod” command without any parameter will start a standalone instance, without any access control.

Now before running MongoDB instance with access control, we need to create one admin user in admin database.

To create an admin user on the local MongoDB server first connect local MongoDB server using command prompt, type mongo on console as we did in our previous step.

Once you have connected to your local server, use “admin” database.

use admin

In MongoDB, admin database is a master database for MongoDB server. First, we will create user to manage users on this server. This user will have access only to manage users on the server not to a database. We will execute the below code.

use admin
db.createUser(
{
user: "usertempadmin",
pwd: "12345",
roles: [ { role: "userAdmin", db: "admin" } ]
}
)

Your screen will look like below.

mongodb create new user consol

Here “usertempadmin” is the user admin on the admin database. In this case admin will be a user authentication database for user “usertempadmin”.

Once you have created a user type “quit()” on console to exit. Stop your mongod instance using ” ctrl+c ” on your command prompt window.

How to Start MongoDB Instance with Authentication

To start MongoDB with an access key, start mongod service with –auth parameter.

C:\Program Files\MongoDB\Server\3.4\bin>mongod --auth

Your MongoDB local server now started with authentication module. There are many other ways to do this, in this article I am explaining it with basic examples.

Now to connect MongoDB instance, open new command prompt and go to MongoDB folder location and type the below command.

mongo --port 27017 -u "usertempadmin" -p "12345" --authenticationDatabase "admin"

After successful connection with “usertempadmin” user, execute command “show dbs “, you will able to see a list of databases on the server.

Remember as we create “usertempadmin” user as “useradmin” this user don’t have permission to read or write the database. To verify this execute the below code.

use blog
switched to db blog

Now when you will run the command to see the collection in this database. as below

use collections

You will get an error message  “errmsg” : “not authorized on blog to execute command { listCollections: 1.0, filter: {} }”

mongodb authentication error

 

This is right error message. Now we will create one more user with root rights, use the below code.

use admin
db.createUser(
{
user: "userroot",
pwd: "12345",
roles: [ { role: "root", db: "admin" } ]
}
)

Once we created this user, quit from the command prompt and login using the below code.

mongo --port 27017 -u "userroot" -p "12345" --authenticationDatabase "admin"

Now use blog database and execute command db.bloguser.findOne()

You will able to see the data from the collection “bloguser”.

In the above example, we created a user in the admin database because of that we used the authentication database as “admin”. If you create a user in “blog” database, then you will use “blog”as authentication database.

use blog
db.createUser(
{
user: "testuser",
pwd: "12345",
roles: [
{ role: "readWrite", db: "blog" }

]
}
) 

and then login as

mongo --port 27017 -u "testuser" -p "12345" --authenticationDatabase "blog"

I will stop here! In this article I have covered MongoDB basic for local MongoDB instance. I hope you have learn something new here. In my next article I will cover how to connect to MongoDB remote server, how to connect MongoDB atlas cloud service, how to install your MongoDB instance on the Amazon EC2 and how to import your local data on the MongoDB remote server.

Leave a Reply

I'm Yogesh Kadvekar, a Technology Consultant, Computer Engineer by education, tech writer and problem solver. I love startups. I love hiking, sports, arts and Stock market. Say hello!

%d bloggers like this: