33
basics JERWIN ROY J Database Adminstrator [email protected]

Mongo DB basics

Embed Size (px)

Citation preview

Page 1: Mongo DB basics

basics JERWIN ROY J Database Adminstrator [email protected]

Page 2: Mongo DB basics

Agenda★ Introduction★ MongoDB Installation -yum -binary★ Roles in MongoDb★ User creation★ Basic commands★ Trace Slow queries★ Important monitoring commands

Page 3: Mongo DB basics

IntroductionWhat is NoSQL database?

A NoSQL or Not Only SQL database provides a mechanism for storage and retrieval of data other than the tabular relations used in relational databases. Motivations for this approach include simplicity of design, horizontal scaling and finer control over availability. 

What is mongodb?

MongoDB is a cross-platform, document oriented database that provides, high performance, high availability, and easy scalability. MongoDB works on concept of collection and document. It is also one of the leading NoSQL database.

Page 4: Mongo DB basics

Why should we use MongoDB?

➔ Document Oriented Storage : Data is stored in the form of JSON style documents

➔ Index on any attribute

➔ Replication & High Availability

➔ Auto-Sharding

➔ Rich Queries

➔ Fast In-Place Updates

➔ Map Reduce functions

➔ Professional Support By MongoDB

Page 5: Mongo DB basics

Database

Database is a physical container for collections. Each database gets its own set of files on the file system. A single MongoDB server typically has multiple databases.

Collection

Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A collection exists within a single database. Collections do not enforce a schema. Documents within a collection can have different fields. Typically, all documents in a collection are of similar or related purpose.

Document

A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection's documents may hold different types of data.

Page 6: Mongo DB basics

Relationship of RDBMS terminology with MongoDB

Page 7: Mongo DB basics

Installation - yum1.Create a repo file as below: vim /etc/yum.repos.d/mongodb.repo2.For 64-bit systems type the below information in repo file and save.[mongodb-org-3.0]name=MongoDB 3.0 Repositorybaseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64/gpgcheck=0enabled=1

Page 8: Mongo DB basics

3.To install all the packages of mongodb issue the below command: yum install mongodb-org4.Start the installed mongodb server using the below command: service mongod start5.The server is now started and to login to the mongo shell issue the below command: mongoNo need to include the port because we are running it on the default port(27017).

Page 9: Mongo DB basics

6.To check the current status of mongod issue the below command: service mongod status7.To stop the running mongod server use the below command: service mongod stop

8.To change the data directory with a new one,stop the current running instance and go to the config file(/etc/mongod.conf) make the changes then save.9.Now start the mongodb,it works with the new data directory.Make sure that the data directory has mongod user permission.

Page 10: Mongo DB basics

1.The mongodb binary are found in the official page(https://www.mongodb.org/downloads).2.Download the binary using wget wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.0.4.tgz3.Now extract the downloaded file using the below command: tar zxf mongodb-linux-x86_64-3.0.3.tgz4.Now rename the extracted(mongodb-linux-x86 64-2.6.3) file into mongodb mv mongodb-linux-x86 64-2.6.3 mongodb

Installation - binary

Page 11: Mongo DB basics

5.Create a data directory using the below command mkdir -p /home/data/db6: Create an user mongo user using the following command useradd mongod

7.Change the ownership of the files in the source and data directory using the following

command chown -R mongod.mongod /home/data/new chown -R mongod.mongod /home/data/db/

Page 12: Mongo DB basics

7.Create a configuration file in any directory say vim /etc/mongod.conf

8.Now add the following details as shown below:dbpath = /home/data/dblogpath = /home/data/mongodb.loglogappend = trueport = 27017auth = true

Page 13: Mongo DB basics

9.Open the script file /etc/init.d/mongod vim /etc/init.d/mongod10.Make the change path in the CONFIGFILE="/etc/mongod.conf" with your config file path.

11.Start the mongodb server using the below command: service mongod start

Page 14: Mongo DB basics

5.The server is now started and to login to the mongo shell issue the below command: mongo

6.To check the current status of mongod issue the below command: service mongod status7.To stop the running mongod server use the below command: service mongod stop

Page 15: Mongo DB basics

Roles in MongoDBSuper roles:readAnyDatabase-reads any databasereadWriteAnyDatabase-reads & writes any databaseuserAdminAnyDatabase-user admin role to any databasedbAdminAnyDatabase-database admin any database

DB user roles:read-reads current databasereadWrite-reads & writes current databadsedbAdmin-access to system. collections in current dbuserAdmin-create,modify roles & users in current dbdbOwner-readWrite, dbAdmin & userAdmin

Page 16: Mongo DB basics

Cluster roles:hostManager-monitor,manage,kill & repair dbclusterMonitor-read only access to monitoring toolsclusterManager-all operations to manage db except dropclusterAdmin- can drop & combo of clusterManager, clusterMonitor, & hostManager.

Backup roles:backup-to take bakuprestore-to restore the backup files

Page 17: Mongo DB basics

Creating a userRoot user: Provides access to the operations readWriteAnyDatabase, dbAdminAnyDatabase, userAdminAnyDatabase and clusterAdmin roles combined. It does not include any access to collections that begin with the system. prefix.Create admin users in the admin database so that they can access all dbs.

use admindb.createUser( { user: “root", pwd: “rootabc", roles: [“root” ] } )

Page 18: Mongo DB basics

So after creating the user it is possible to login only with user beacuse we have enabled auth.

super user:use admindb.createUser( { user: "superuser", pwd: "admin", roles: [ "userAdminAnyDatabase", "dbAdminAnyDatabase", "readWriteAnyDatabase"] } )

Page 19: Mongo DB basics

Read user for a database:

use database

db.createUser( {

user: "read",pwd: "password",roles:

[ { role: "read", db: "database" }

] })

Page 20: Mongo DB basics

monitoring user:

For the monitoring this user serves best:

db.createUser({user: "monitoring",pwd: "abc123",roles: [ "clusterMonitor" ]})

Page 21: Mongo DB basics

Verify the privilege using:

db.runCommand( {

usersInfo:"admin",showPrivileges:true

})

Kill a query: Find the opid using currentop(_) command. db.killOp(opid)

opid-it is the operation id of a particular query.

Page 22: Mongo DB basics

Basic commands A few basic commands that are used in the mongodb client are listed below:

use new_db -Uses the databasespecifieddb -Displays the current database nameshow dbs -Displays list of all databasesshow collections -Displays list of all collectionsdb.dropDatabase() -Drops the current database in usedb.collection.drop() -Drops the collection mentioned

Page 23: Mongo DB basics

Trace Slow queries Slow queries can be traced using database profiler.Mongodb has three levels of profiling,each with unique feature.db.setProfilingLevel(0) ->no profilingdb.setProfilingLevel(1) ->slow queriesdb.setProfilingLevel(2) ->all queries

To check the current profiling level use the below command:db.getProfilingStatus()

All the traced slow queries will be present in predefined collection system.profile in the local database.To view the queries fire the below command:db.system.profile.find()

Page 24: Mongo DB basics

Important Monitoring commandsServerstatus - Similar to mysql show processlist

db.serverStatus().uptimedb.serverStatus().connectionsdb.serverStatus().opcounters

Page 25: Mongo DB basics

currentop():Display all the documents that contains information on in-progress operations for the database instance

To view the current active queries in the database:db.currentOp( { "active" : true

})

To view all active read queries:db.currentOp().inprog.forEach( function(d){ if(d.active && d.lockType == "read") printjson(d) })

Page 26: Mongo DB basics

To view all active write queries:

db.currentOp().inprog.forEach( function(d){ if(d.waitingForLock && d.lockType != "write") printjson(d) })

To view the queries that are waiting for a lock and not a read:

db.currentOp().inprog.forEach( function(d){ if(d.waitingForLock && d.lockType != "read") printjson(d) })

Page 27: Mongo DB basics

To view the queries that are running more than ‘x(2)’ seconds in the database:

db.currentOp( { "active" : true, "secs_running" : { "$gt" : 2} }

)

Page 28: Mongo DB basics

db.stats()- Statistics about a database

Page 29: Mongo DB basics

db.collection.stats(): Statistics about a particular collection

Page 30: Mongo DB basics

rs.status(): Statistics about a replica set

Page 31: Mongo DB basics

rs.printReplicationInfo()- Replication info such as sync between the replica

rs.printSlaveReplicationInfo()- Slave replication details

Page 32: Mongo DB basics

db.isMaster() - To check whether a replica is master,true returns its a master

Page 33: Mongo DB basics

Thank You