CRUD Operation in MongoDB
PRACTICAL
5(a): CRUD Operation in MongoDB Using Command Line Interface (CLI)
In
our previous practical we came across how to 'Install, Setup and Run MongoDB in
Windows'. In this particular session we we’ll see basic crud operation using Mongo Shell commands
We
will discuss how to create a database in MongoDB, how to create a table in
MongoDb, how to insert data in a MongoDB Collection and how to update and
delete data from MongoDB table(Collection)
·
Start MongoDB Shell from Command Line
Start
MongoDB shell with 'mongod' command,
you will see following screen as shown below.
·
Create connection in MongoDB
Open
an another instance of command prompt and connect MongoDB by supplying 'mongo' command, you will see following
screen ready to work in Mongo.
·
Show all Databases in MongoDB
To
see all existing database in MongoDB, supply 'show dbs' command, you will see following output containing all
exiting database:
·
Create a Database in MongoDB
In
MongoDB it is not required to create a database before using it, just supply 'use databaseName' and you will be
switched to specified database even if the database don't exist, mongo will
create the database on the fly at the time you use it.
·
Create a Table in MongoDB
Same
as creating a database, we don’t need to create a table before using it, just
switch to the database in which you want to create a new table and supply
'db.nextTable.insert({column1:"value",column2:"value",...})' the very first time you insert the data in a table
Mongo will create the table on the fly if it does not exists already.
·
Insert Data in a Table(Collection) in MongoDB
To
insert data in a table, use command
'db.nextTable.insert({column1:"value",column2:"value",...})'
or
'db.nextTable.save({column1:"value",column2:"value",...})',
as shown below :
·
Select or Retrieve data from a Table(Collection) in
MongoDB
To
select all rows from a table supply command 'db.newTable.find()', you will get an output as shown below :
·
Update data or row in a Table(Collection) in MongoDB
To
update data or a row in a table supply command
'db.newTable.update({identifierColumn:value},{$set:{columnToChange:"newValue"}})',
you will get an output as shown below :
·
Delete data or a row in Table(Collection) in MongoDB
To
delete data or a row in a table supply command
'db.newTable.remove({identifierColumn:value})',
you will get an output as shown below :
.
Comments
Post a Comment