Tuesday, May 12, 2020

Basic Database Operations

The Mongo Shell

Open the command prompt and navigate to the /bin folder of the MongoDB using the cd command and execute the command mongod there. This will initiate the MongoDB server. We have to keep this command prompt window alive, as this is running MongoDB.

To stop the MongoDB server, simply enter exit and press Enter.

Now, Open another command prompt and navigate to the /bin folder of the MongoDB again and execute the command mongo. This will open up the client to run the MongoDB commands. Please note that you can exit the Mongo shell by running quit() and the Mongo daemon by pressing Ctrl + C at any time.

MongoDB: Creating a Database

In the command prompt window in which we ran the mongo command, after successfully connecting to the mongodb, just type the command the following :

use database_name

This will create a new database with the name database_name if there is no database already present with the same name. If a database already exists with the mentioned name, then it just connects to that database.

            use studentdb

switched to db studentdb

> 

In the above picture, it creates a new database called studentdb and will also connect to the same.

To check the currently connected database, type in db in the command prompt window, and you will get the name of the current database as a result.

db

studentdb

>  

To see the list of all the databases in MongoDB, use command show dbs

show dbs

admin     0.000GB

config    0.000GB

local     0.000GB

>  

Please note that the newly created database studentdb has not been listed after running the above command. This is because, there is no records have been inserted into that database yet. Just insert one record and then run the command again as shown below:

To Insert data, run the following command. Don’t worry about it, we will learn this in detail in next lessons.

db.studentdb.insert({name : "Pankaj Kapoor" }) 

NOTE: In MongoDB, test will be the default database. If no database is created, then all the data will be stored in the test database.

MongoDB: Drop a Database

First check the list of databases available as shown below, using the show dbs command.

show dbs

admin            0.000GB

config           0.000GB

local            0.000GB

studentdb        0.000GB

test             0.000GB

>  

If you want to delete newly created database studentdb. Run the below command to delete the database. Before deleting the database, connect to the required database which is to be deleted.

db.dropDatabase()                                                                       

       use studentdb

switched to db studentdb

db.dropDatabase()

"dropped" : "studentdb""ok" : 1 }

>  

Now again check the list of databases, to verify whether the database is deleted or not.

show dbs

admin     0.000GB

config    0.000GB

local     0.000GB

test      0.000GB

>  

Note that the database studentdb has been deleted and hence, it will not be listed in the list of the databases. 


MongoDB: Creating a Collection

In traditional databases, we generally use schema (or tables), but there's no such hard and fast rule for NoSQL Databases. We have Collections instead of Tables. Basically, collections hold the documents or records.

In MongoDB a collection is automatically created when it is referenced in any command. For example, if you run an insert command :

db.employee.insert({

    name: "Pankaj Kapoor"

})

MongoDB: Creating Collection Explicitly 

Above command will create a collection named student if it doesn't exist already in the database. But we can explicitly create a collection using the createCollection() command. The syntax of createCollection method is:

db.createCollection(nameoptions)

In the above command, name will be the name of the collection and options is a document which can be used to specify configurations for the collection.

Following are the available configuration options for creating a collection in MongoDB:

Field

Type

Description

capped

boolean

(Optional) To create a capped collection, where in we specify the the maximum size or document counts to prevent it from growing beyond a set maximum value.

size

number

(Optional) To specify the maximum size in bytes for a capped collection. If a collection is capped and reaches its maximum size limit, MongoDB then removes older documents from it to make space for new.

max

number

(Optional) This can be used to specify the maximum number of documents allowed in a capped collection.

validator

document

(Optional) Validates any document inserted or updated against provided validation rules.

MongoDB: Creating a Capped Collection

We can create a capped collection using the following command.

db.createCollection("employee", { capped : truesize : 5242880max : 2000 } )

This will create a collection named student, with a maximum size of 5 megabytes and a maximum of 2000 documents.

MongoDB: Drop a Collection

Any collection in a database in MongoDB can be dropped easily using the following command:

db.collection_name.drop()

drop() method will return true is the collection is dropped successfully, else it will return false.