Working with mongo shell

PrerequisiteVisit my blogs 

Install Run and Connect to MongoDB on Mac

           OR 

Install Run and Connect to MongoDB on Windows

Create mongo database and user

After connecting to mongo shell using the command "$ mongo" , follow the below instructions to create mongo database and user.


Show all databases

Print a list of all databases on the server.

> show dbs

Output :

admin 0.000GB

config 0.000GB

local 0.000GB

To display the database you are using, type db:

The operation should return ‘test’, which is the default database.

> db

Output :

test

Switch databases

To switch databases, type the ‘use <db>’ helper:

> use test

Output :

switched to db test 

Create Admin user with access to any database


> use admin

Output :

switched to db admin


> db

Output :

admin


Create Admin user.


db.createUser({user:"admin",pwd:"admin",roles:[{role:"userAdminAnyDatabase",db:"admin"},"readWriteAnyDatabase"]})

Output :

Successfully added user: {

"user" : "admin",

"roles" : [

{

"role" : "userAdminAnyDatabase",

"db" : "admin"

},

"readWriteAnyDatabase"

]

}

           db.createUser() returns a duplicate user error if the user already exists on the database. 

Create users for a database with readWrite access


> use test

Output :

switched to db test


> db

Output :

test


Create user <in database test>

                   >  db.createUser({user:"aarav",pwd:"sharma",roles:[{role:"readWrite",db:"test"}]})

Output :

Successfully added user: {

"user" : "aarav",

"roles" : [

{    

"role" : "readWrite",

"db" : "test"

}

]

}

          db.createUser() returns a duplicate user error if the user already exists on the database. 

Test spring-boot-reference using curl

Next, to create collections in recently created database run spring-boot-reference application following the steps in ReadMe documentation of my github repository:

 
 https://github.com/aarav27/spring-boot-reference
 

Once the application is up and running, you can add new enrollee using the curl script available in link below:

 

https://github.com/aarav27/spring-boot-reference/blob/master/src/test/resources/curl

 

Print a list of all databases on the server.

> show dbs

Output :

admin 0.000GB

config 0.000GB

local 0.000GB

test 0.000GB

Show Collections under database test

Show collections

> show collections

Output :

enrollee

Show/Select all the recorded under collection enrollee

Print a list of all databases on the server.

db.enrollee.find({})

Output :

{
   "_id":"1",
   "personId":"101",
   "enrolleeName":"George Washington",
   "_class":"org.sharma.aarav.spring.boot.reference.data.model"

}

Comments

Popular posts from this blog

IntelliJ IDE Setup on Mac

Basic Setup for Java on Mac and Windows

Install, Run and Connect to MongoDB on Windows

Install, Run and Connect to MongoDB on Mac