Basics of MongoDB Shell

With MongoDB installed, (see Install Mongodb on Fedora 23)

get the server running with,

$ mongod

and remember this will hang, so open a new tab in your terminal to continue. In fedora this will be

Ctrl+shift+T

In that new terminal,

$ sudo mongo

Let us see what if any databases exist on the server,

 > show dbs

Say I have a database called ‘mydb’. Now if we want to use that databse we must use,

 > use mydb

To see what ‘collections’ or ‘tables’ exist in this database use,

 > show collections

If there is a collection called ‘movie’ and we’d like to look at it’s contents use,

 > db.movie.find()

To create a new database just start using it,

 > use newDB

Using Python to Connect to a MongoDB

This code uses Python to connect to a mongoDB, allowing for print out of the names of all the databases and the names of the collections in a given database, which is in this example is called ‘mydb’.

import pymongo
def mongo_connect():
    try:
         conn = pymongo.MongoClient()
         print "Mongo is connected"
         return conn
    except pymongo.errors.ConnectionFailure, e:
         print "Could not connect to MongoDB: %s" % e
conn  = mongo_connect()
print "Database names: %s" % conn.database_names()
db = conn.mydb
coll = db.collection_names()

print "Database name: %s" % db.name
print "Collection names: %s" % coll

Install Mongodb on Fedora 23

To install Mongodb on Fedora 23 go to

https://www.mongodb.org/downloads

On the Linux tab go to version RHEL 7 Linux 64-bitmongodbSreenshot

$ wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-3.2.3.tgz

Untar the tarball

$ tar -zxvf mongodb-linux-x86_64-rhel70-3.2.3.tgz
$ echo $PATH
$ sudo ln -s ~/Downloads/mongodb-linux-x86_64-rhel70-3.2.3/bin/mongo /usr/local/bin/mongod
$ mongod --version
MongoDB shell version: 3.2.3
$ mongo --version
MongoDB shell version: 3.0.8

Make the directory /data/db

$ mkdir -p /data/db/

Change the permissions on both /data and /data/db

$ sudo chmod 777 /data
$ sudo chmod 777 /data/db

Make sure you are in the mongo directory in /Downloads, ~/Downloads/mongodb-linux-x86_64-rhel70-3.2.3/bin/mongo . Next copy all here to /usr/local/bin/

$ cp * /usr/local/bin

From anywhere run the server with

$ mongod

At the end of the output you should get

 ....... waiting for connections on port 27017

In your browser navigate to localhost:27017
Selection_005
I found that on Fedora both mongod and mongo start the server. mongo should start the Mongodb shell only.

$ mongo

Should run the mongo shell, however on fedora you will need to use,

 $ sudo mongod

And this only works when the Mongodb server is already running.
Continue to Basics of MongoDB Shell