Monday, March 14, 2022

R20-MongoDB Lab Solutions for CSE (DS) JNTUK

 JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY KAKINADA 

KAKINADA – 533 003, Andhra Pradesh, India  

    List of Experiments:

 1. MongoDB installation and configuration in windows. 

2. Demonstrate how to create and drop a database in MongoDB.

 3. Creating the Collection in MongoDB on the fly 

4. Creating collection with options before inserting the documents and drop the collection created. 

5. MongoDB insert document a. Insert single document b. Insert multiple documents in collection 

6. Querying all the documents in json format and Querying based on the criteria. 

7. MongoDB update document a. Using update() method. b. Using save() method. 

8. MongoDB delete document from a collection. a. Using remove() method. b. Remove only one document matching your criteria c. Remove all documents

 9. MongoDB Projection 

10. limit() ,skip(), sort() methods in MongoDB 

11. MongoDB indexing

 a. Create index in MongoDB 

b. Finding the indexes in a collection 

c. Drop indexes in a collection

 d. Drop all the indexes 

12. MongoDB with java and PHP 

a. Create  a simple application that uses MongoDB with Java 

 b. Create  a simple application that uses MongoDB with PHP 

https://beginnersbook.com/2017/09/mongodb-tutorial/

Record By RVS@RISE


---------------------------------------------------------------------------------------------------------------------------

EXPERIMENT-1

  1. MongoDB installation and configuration in windows.

AIM:  MongoDB installation and configuration in windows.


PROCEDURE:

Install MongoDB On Windows To install the MongoDB on windows, first doownload the latest release of MongoDB from http://www.mongodb.org/downloads Make sure you get correct version of MongoDB depending upon your windows version. To get your windows version open command prompt and execute following command.

C:\>wmic os get osarchitecture

OSArchitecture

64-bit

C:\>

32-bit versions of MongoDB only support databases smaller than 2GB and suitable only for testing and evaluation purposes. Now extract your downloaded file to c:\ drive or any other location. Make sure name of the extracted folder is mongodb-win32-i386-[version] or mongodb-win32-x86_64-[version]. Here [version] is the version of MongoDB download. Now open command prompt and run the following command

C:\>move mongodb-win64-* mongodb

1 dir(s) moved.

C:\>

In case you have extracted the mondodb at different location, then go to that path by using command cd FOOLDER/DIR and now run the above given process. MongoDB requires a data folder to store its files. The default location for the MongoDB data directory is c:\data\db. So you need to create this folder using the Command Prompt. Execute the following command sequence C:\>md data

C:\md data\db

If you have install the MongoDB at different location, then you need to specify any alternate path for \data\db by setting the path dbpath in mongod.exe. For the same issue following commands

In command prompt navigate to the bin directory present into the mongodb installation folder. Suppose my installation folder is D:\set up\mongodb 

C:\Users\XYZ>d:

D:\>cd "set up"

D:\set up>cd mongodb

D:\set up\mongodb>cd bin

D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"

D:\set up\mongodb\bin>mongo.exe

MongoDB shell version: 3.4.3

Output:


https://blogger.googleusercontent.com/img/a/AVvXsEjEMheKHyFPCyGkBiZ1MOFuczAmXE98qFX11D2E7dnLPm2qLFWIfn02iqxgoHKCJVdDIkKPBbAEcfK9PRbtcbRjtZLKrkBFpMptDC4USIFB57ubqFjZZWRsSVA0XX8-yGyDk71Qv4JjLyLUH53OQvD1-_Ks6JdTHN-XuxE05QFyncjpgQvQWNhh7P2z5w=s612          

                

OR  Installing MongoDB


                     

EXPERIMENT-2

  1. Demonstrate how to create and drop  database in MongoDB.


AIM: Demonstrate how to create and drop a database in  MongoDB.


PROCEDURE:

The use Command MongoDB use DATABASE_NAME is used to create database. The command will create a new database, if it doesn't exist otherwise it will return the existing database. Syntax: Basic syntax of use DATABASE statement is as follows:

use DATABASE_NAME

Example: If you want to create a database with name <mydb>, then use DATABASE statement would be as follows: >use mydb.

switched to db mydb

To check your currently selected database use the command db >db mydb.

If you want to check your databases list, then use the command show dbs.

>show dbs local    

0.78125GB test     

0.23012GB

Your created database (mydb) is not present in list. To display database you need to insert atleast one document into it.


 >db.movie.insert({"name":"tutorials point"})

>show dbs local     

0.78125GB mydb      

0.23012GB test     

 0.23012GB

In mongodb default database is test. If you didn't create any database then collections will be stored in test database.

The dropDatabase () Method

MongoDB db.dropDatabase () command is used to drop a existing database. Syntax: Basic syn tax of dropDatabase () command is as follows:

db.dropDatabase()

This will delete the selected database. If you have not selected any database, then it will delete default 'test' database Example: First, check the list available databases by using the command show dbs

>show dbs

local      0.78125GB

mydb       0.23012GB

 test       0.23012GB

 If you want to delete new database <mydb>, then dropDatabase() command would be as follows: >use mydb switched to db mydb.


>db.dropDatabase()

>{ "dropped" : "mydb", "ok" : 1 }

Now check list of databases

>show dbs local     

 0.78125GB test      

0.23012GB 






Output:


C:\Users\LIKHITHA\OneDrive\Pictures\Screenshots\2022-06-14.png

                   



EXPERIMENT-3

  1. Creating the Collection in MongoDB.

AIM: Creating the Collection in MongoDB.


PROCEDURE:

MongoDB db.createCollection(name, options) is used to create collection.

Syntax:

Basic syntax of createCollection() command is as follows

db.createCollection(name, options)

Options parameter is optional, so you need to specify only name of the collection. Following is the list of options you can use:

While inserting the document, MongoDB first checks size field of capped collection, then it checks max field

Basic syntax of createCollection() method without options is as follows

>use test switched to db test

>db.createCollection("mycollection")

{ "ok" : 1 }

You can check the created collection by using the command show collections

>show collections

mycollection

system.indexes.

C:\Users\LIKHITHA\OneDrive\Pictures\Screenshots\2022-06-14 (1).png










                   

                

EXPERIMENT-4

  1. Creating collection with options before inserting the documents and drop the collection created.


AIM: Creating collection with options before inserting the documents and drop the collection created.


PROCEDURE:

In mongodb you don't need to create collection. MongoDB creates collection automatically, when you insert some document.

>db.tutorialspoint.insert({"name" : "tutorialspoint"})

>show collections mycol mycollection

 system.indexes

> MongoDB's db.collection.drop() is used to drop a collection from the database.

Syntax:

Basic syntax of drop() command is as follows

First, check the available collections into your database mydb

>use mydb

switched to db mydb

>show collections

 mycol mycollection

 system.indexes

 tutorialspoint

> Now drop the collection with the name mycollection

>db.tutorialpoint.drop()

true

> Again check the list of collections into database

>show collections

 mycol 

system.indexes


Output:


C:\Users\LIKHITHA\OneDrive\Pictures\Screenshots\2022-06-14 (2).png










                 

EXPERIMENT-5

  1. MogoDB Insert Document

  1. Insert single document.

  2. Insert multiple documents in collection.


AIM: MogoDB Insert Document


PROCEDURE:

  1. Insert single document

The insert() Method

To insert data into MongoDB collection, you need to use MongoDB's insert() or save()method

Example :

db.post.insert([{

title: 'MongoDB Overview',

description: 'MongoDB is no sql database',

by: 'tutorials point',

url: 'http://www.tutorialspoint.com',

tags: ['mongodb', 'database', 'NoSQL'],

likes: 100

},

{

title: 'NoSQL Database',

description: 'NoSQL database doesnt have tables',

by: 'tutorials point',

url: 'http://www.tutorialspoint.com',

tags: ['mongodb', 'database', 'NoSQL'],

likes: 20,

comments: [{

user:'user1',

message: 'My first comment',

dateCreated: new Date(2013,11,10,2,35),

like: 0

}]}

])

To insert the document you can use db.post.save(document) also. If you don't specify _id in the document

then save() method will work same as insert() method. If you specify _id then it will replace whole data of

document containing _id as specified in save() method.

  1. Insert multiple documents in collection.

To insert multiple documents we can use insertMany() - which takes an array of documents as parameter. When executed, it returns multiple ids for each document in the array. To drop the collection, use drop() command. Sometimes, when doing bulk inserts - we may insert duplicate values. Specifically, if we try to insert duplicate _ids, we'll get the duplicate key error:

Creating new collection:

>db.create("startup")

{ ok: 1 }

inserting many documents

>db.startup.insertMany([

  {_id:"id1", name:"Uber"},

  {_id:"id2", name:"Airbnb"},

  {_id:"id4", name:"Ola"},

  ]  );

>db.startup.insertMany(  [

  {_id:"id4", name:"Uber"},

  {_id:"id5", name:"Airbnb"},

  {_id:"id6", name:"Ola"},

  ]);

showing all documents

db.startup.find()

{ _id: 'id1', name: 'Uber' }

{ _id: 'id2', name: 'Airbnb' }

{ _id: 'id4', name: 'Uber' }

{ _id: 'id5', name: 'Airbnb' }

{ _id: 'id6', name: 'Ola' }


                   







EXPERIMENT-6

6. Querying all the documents in json format and Querying based on the criteria


AIM: Querying all the documents in json format and Querying based on the criteria. 


PROCEDURE:

creating new collection.

>db.create("startupnew")

{ ok: 1 }

inserting many documents

>db.startupnew.insertMany(  [

  {_id:"id1", name:"Uber"},

  {_id:"id2", name:"Airbnb"},

  {_id:"id4", name:"Ola"},

  ]);

>db.startupnew.insertMany(  [

  {_id:"id4", name:"Uber"},

  {_id:"id5", name:"Airbnb"},

  {_id:"id6", name:"Ola"},

  ] );

showing all documents

db.startupnew.find()

{ _id: 'id1', name: 'Uber' }

{ _id: 'id2', name: 'Airbnb' }

{ _id: 'id4', name: 'Uber' }

{ _id: 'id5', name: 'Airbnb' }

{ _id: 'id6', name: 'Ola' }

Qureying whose name is Uber


>db.startupnew.find({name:"Uber"})

{ _id: 'id1', name: 'Uber' }

{ _id: 'id4', name: 'Uber' }


Output:


                  https://blogger.googleusercontent.com/img/a/AVvXsEgVLc5SXUezUmOugGQPLaz_b45VXDOT-jQuLPTOVpV4S7_HQ012wFCjD_2-SYrQPl6S0df2_uDFIoXVRoM_0Fbq82hLaukEtMON8PA33dhxWeDHKhE9dYFZSI1J2jbmPYjtilszf_tZBpBirJhTDICKmmBId51pJH88enQJIJNBClFnLinuJV3Q7mHN1w=s1440



EXPERIMENT-7

7. MongoDB update document 

a. Using update() method. 

b. Using save() method.


AIM: MongoDB update document 


PROCEDURE:

  1. Using update() method

creating new collection

>db.createCollection("startup1")

{ ok: 1 }

inserting many documents

>db.startup1.insertMany([

  {_id:"id1", name:"Uber"},

  {_id:"id2", name:"Airbnb"},

  {_id:"id3", name:"Ola"},

  {_id:"id4", name:"Amazon"},

  {_id:"id5", name:"Microsoft"},

  {_id:"id6", name:"Google"},

  ]);

showing all documents

>db.startup1.find()

  {_id:"id1", name:"Uber"}

  {_id:"id2", name:"Airbnb"}

  {_id:"id3", name:"Ola"}

  {_id:"id4", name:"Amazon"}

  {_id:"id5", name:"Microsoft"}

  {_id:"id6", name:"Google"}

The update() method updates values in the existing document.

By default mongodb will update only single document, to update multiple you need to set a paramter 'multi' to true.

>db.startup1.update({'name':'Ola'},{$set:{'name':'New MongoDB By RVS'}},{multi:true})


  1. Using save() method.

The save() method replaces the existing document with the new document passed in save() method

>db.startup1.save({

"_id" : "id6", "name":"MangoDB  Document Replacing "

})

showing all documents after updation

>db.startup1.find()

  {_id:"id1", name:"Uber"}

  {_id:"id2", name:"Airbnb"}

  {_id:"id3", name:"Ola"}

  {_id:"id4", name:"Amazon"}

  {_id:"id5", name:"Microsoft"}

  {_id:"id6", name:"MangoDB  Document Replacing "}

                 


 EXPERIMENT-8

8. MongoDB delete document from a collection. 

a. Using remove() method. 

b. Remove only one document matching your criteria 

c. Remove all documents.


AIM: MongoDB delete document from a collection. 

a. Using remove() method. 

b. Remove only one document matching your criteria 

c. Remove all documents.


PROCEDDURE:

  1. Using remove() method.

MongoDB's remove() method is used to remove document from the collection.

remove() method accepts two  parameters. One is deletion criteria and second is just One flag.

1. deletion criteria : (Optional)  deletion criteria according to documents will be removed.

2. justOne : (Optional) if set to true or 1, then remove only one document.

Syntax:

   Basic syntax of remove() method is as follows

  >db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)




Example:

creating new collection “startupnew”

>db.createCollection("startupnew")

{ ok: 1 }

inserting many documents 

 >db.startupnew.insertMany([

  {_id:"id1", name:"Uber"},

  {_id:"id2", name:"Airbnb"},

  {_id:"id4", name:"Ola"},

  ] );

 >db.startupnew.insertMany( [

  {_id:"id4", name:"Uber"},

  {_id:"id5", name:"Airbnb"},

  {_id:"id6", name:"Ola"},

  ] );

 showing all documents

db.startupnew.find()

{ _id: 'id1', name: 'Uber' }

{ _id: 'id2', name: 'Airbnb' }

{ _id: 'id4', name: 'Uber' }

{ _id: 'id5', name: 'Airbnb' }

{ _id: 'id6', name: 'Ola' }

Remove only one document matching your criteria :

>db.startupnew.remove({'name':'Ola'})

showing all documents after removing  “Ola”

db.startupnew.find()

{ _id: 'id1', name: 'Uber' }

{ _id: 'id2', name: 'Airbnb' }

{ _id: 'id4', name: 'Uber' }

{ _id: 'id5', name: 'Airbnb' }

Following example will remove all the documents whose title is 'MongoDB Overview'


  1. Remove only one document matching your criteria 

If you don't specify deletion criteria, then mongodb will delete whole documents from the collection. 

This is equivalent of SQL's truncate command.

>db.startupnew.remove()

After removing all documents







                 




                    EXPERIMENT-9

9. MongoDB Projection

AIM: MongoDB Projection


PROCEDURE:

In mongodb projection meaning is selecting only necessary data rather than selecting whole of the data of adocument. If a document has 5 fields and you need to show only 3, then select only 3 fields from them.

The find() Method :

MongoDB's find() method accepts second optional parameter that is list of fields that you want to retrieve. In MongoDB when you execute find() method, then it  displays all fields of a document. To limit this you need to set list of fields with value 1 or 0. 1 is used to show the filed while 0 is used to hide the field.

Syntax:

Basic syntax of find() method

with projection is as follows

>db.COLLECTION_NAME.find({},{KEY:1})

Example :

creating new collection “startupnew”

>db.createCollection("startupnew")

{ ok: 1 }

Inserting many documents 

>db.startupnew.insertMany([

  {_id:"id1", name:"Uber"},

  {_id:"id2", name:"Airbnb"},

  {_id:"id4", name:"Ola"},

  ] );

showing all documents in startupnew

db.startupnew.find()

{ _id: 'id1', name: 'Uber' }

{ _id: 'id2', name: 'Airbnb' }

{ _id: 'id4', name: 'Ola' }


Following example will display the title of the document while quering the document.

>db.startupnew.find({},{"name":1,_id:0})

{  name: 'Uber' }

{  name: 'Airbnb' }

{  name: 'Ola' }

> Please note _id field is always displayed while executing find() method, if you don't want this field,then  you need to set it as 0.














EXPERIMENT-10

10. limit() ,skip(), sort() methods in MongoDB


AIM: To show limit() ,skip(), sort() methods in MongoDB.


PROCEDURE:


The limit() Method :

To limit the records in MongoDB, you need to use limit() method. limit() method accepts one number type argument, which is number of documents that you want to displayed. Syntax: Basic syntax of limit() method is as follows

>db.COLLECTION_NAME.find().limit(NUMBER)

creating new collection “startupnew”

 >db. createCollection ("startupnew")

{ ok: 1 }

 inserting many documents

 >db.startupnew.insertMany( [

  {_id:"id1", name:"Uber"},

  {_id:"id2", name:"Airbnb"},

  {_id:"id4", name:"Ola"},

  ]);

 showing all documents in startupnew

 db.startupnew.find()

 { _id: 'id1', name: 'Uber' }

{ _id: 'id2', name: 'Airbnb' }

{ _id: 'id4', name: 'Ola' }

 Following example will display only 2 documents while quering the document.

>db.startupnew.find({},{"name":1,_id:0}).limit(2)

{ _id: 'id1', name: 'Uber' }

{ _id: 'id2', name: 'Airbnb' }

If you don't specify number argument in limit() method then it will display all documents from the collection.


The Skip() method:

Apart from limit() method there is one more method skip() which also accepts number type argument and used to skip number of documents.

Syntax:

Basic syntax of skip() method is as follows..

>db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)

 Example:

 Following example will only display only second document.

>db.startupnew.find({},{"name":1,_id:0}).limit(1).skip(1)

{ _id: 'id2', name: 'Airbnb' }

 >Please note default value in skip() method is 0





The sort() Method :

To sort documents in MongoDB, you need to use sort() method. sort() method accepts a document containing list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

 Syntax:

Basic syntax of sort() method is as follows

>db.COLLECTION_NAME.find().sort({KEY:1})

Example :

 Consider the collection startupnew  has the following data

{ _id: 'id1', name: 'Uber' }

{ _id: 'id2', name: 'Airbnb' }

{ _id: 'id4', name: 'Ola' }

 Following example will display the documents sorted by name in descending order.

>db.startupnew.find({},{"name":1,_id:0}).sort({"name":-1})

{ _id: 'id1', name: 'Uber' }

{ _id: 'id4', name: 'Ola' }

{ _id: 'id2', name: 'Airbnb' }

 Please note if you don't specify the sorting preference, then sort() method will display documents in ascending order.




                 





                      EXPERIMENT-11

11. MongoDB indexing

a. Create index in MongoDB

b. Finding the indexes in a collection

c. Drop indexes in a collection

d. Drop all the indexes


AIM: MongoDB indexing

 a. Create index in MongoDB

b. Finding the indexes in a collection

c. Drop indexes in a collection

d. Drop all the indexes


PROCEDURE:

  1. Create index in MongoDB

Indexes support the efficient resolution of queries. Without indexes, MongoDB must scan every document of a collection to select those documents that match the query statement. This scan is highly inefficient and require the mongod to process a large volume of data.

The ensureIndex() Method:

To create an index you need to use ensureIndex() method of mongodb.

Syntax:

 Basic syntax of ensureIndex() method is as follows()

 >db.COLLECTION_NAME.ensureIndex({KEY:1})

Here key is the name of filed on which you want to create index and 1 is for ascending order. To create index in descending order you need to use -1.

Example :-

creating new collection “startupnew”

 >db. createCollection ("startupnew")

{ ok: 1 }

 inserting many documents

 >db.startupnew.insertMany(  [

  {_id:"id1", name:"Uber",description:”US”},

  {_id:"id2", name:"Airbnb",description,”IND”},

  {_id:"id4", name:"Ola",description:”IND”},

  ]  );

 showing all documents in startupnew

 db.startupnew.find()

   {_id:"id1", name:"Uber",description:”US”},

  {_id:"id2", name:"Airbnb",description,”IND”},

  {_id:"id4", name:"Ola",description:”IND”},

>db.startupnew.ensureIndex({"name":1})

                        Or

db.startupnew.createIndex(

{name: 1},

{name: "cab index"}

)

In ensureIndex() method you can pass multiple fields, to create index on multiple fields.

 >db. startupnew.ensureIndex({"name":1,"description":-1})



> ensureIndex() method also accepts list of options (which are optional), whose list is given below:




b)Finding indexes

 You can find all the available indexes in a MongoDB collection by using the getIndexes method. This will return all the indexes in a specific collection. 

db.startupnew.getIndexes()


 c) Dropping indexes

To delete an index from a collection, use the dropIndex method while specifying the index name to be dropped.

 db.startupnew.dropIndex("cab  index")


 d) Dropping all indexes

The dropIndexes command can also drop all the indexes excluding the default _id index.

db.startupnew.dropIndexes()





/*  OLD MANUAL */

Solutions :

1.   1.  MongoDB installation and configuration in windows.

Install MongoDB On Windows To install the MongoDB on windows, first doownload the latest release of MongoDB from http://www.mongodb.org/downloads Make sure you get correct version of MongoDB depending upon your windows version. To get your windows version open command prompt and execute following command

 

C:\>wmic os get osarchitecture

OSArchitecture

64-bit

C:\>

 

32-bit versions of MongoDB only support databases smaller than 2GB and suitable only for testing and evaluation purposes. Now extract your downloaded file to c:\ drive or any other location. Make sure name of the extracted folder is mongodb-win32-i386-[version] or mongodb-win32-x86_64-[version]. Here [version] is the version of MongoDB download. Now open command prompt and run the following command

 

C:\>move mongodb-win64-* mongodb

      1 dir(s) moved.

C:\>

 

In case you have extracted the mondodb at different location, then go to that path by using command cd FOOLDER/DIR and now run the above given process. MongoDB requires a data folder to store its files. The default location for the MongoDB data directory is c:\data\db. So you need to create this folder using the Command Prompt. Execute the following command sequence C:\>md data

C:\md data\db

 

If you have install the MongoDB at different location, then you need to specify any alternate path for \data\db by setting the path dbpath in mongod.exe. For the same issue following commands

 

In command prompt navigate to the bin directory present into the mongodb installation folder. Suppose my installation folder is D:\set up\mongodb 

C:\Users\XYZ>d:

D:\>cd "set up"

D:\set up>cd mongodb

D:\set up\mongodb>cd bin

D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"

 

D:\set up\mongodb\bin>mongo.exe

MongoDB shell version: 3.4.3

 



 

 

2.   2.  Demonstrate how to create and drop a database in MongoDB.

The use Command MongoDB use DATABASE_NAME is used to create database. The command will create a new database, if it doesn't exist otherwise it will return the existing database. Syntax: Basic syntax of use DATABASE statement is as follows:

use DATABASE_NAME

Example: If you want to create a database with name <mydb>, then use DATABASE statement would be as follows: >use mydb

switched to db mydb

To check your currently selected database use the command db >db mydb

If you want to check your databases list, then use the command show dbs.

>show dbs local    

0.78125GB test     

0.23012GB

Your created database (mydb) is not present in list. To display database you need to insert atleast one document into it.

 >db.movie.insert({"name":"tutorials point"})

 

>show dbs local     

0.78125GB mydb      

0.23012GB test     

 0.23012GB

In mongodb default database is test. If you didn't create any database then collections will be stored in test database.

 

The dropDatabase () Method

MongoDB db.dropDatabase () command is used to drop a existing database. Syntax: Basic syn tax of dropDatabase () command is as follows:

db.dropDatabase()

This will delete the selected database. If you have not selected any database, then it will delete default 'test' database Example: First, check the list available databases by using the command show dbs

>show dbs

local      0.78125GB

mydb       0.23012GB

 test       0.23012GB

 >

If you want to delete new database <mydb>, then dropDatabase() command would be as follows: >use mydb switched to db mydb

>db.dropDatabase()

>{ "dropped" : "mydb", "ok" : 1 }

>

Now check list of databases

>show dbs local     

 0.78125GB test      

0.23012GB >

 

3.Creating the Collection in MongoDB.

MongoDB db.createCollection(name, options) is used to create collection.

Syntax:

Basic syntax of createCollection() command is as follows

db.createCollection(name, options)

Parameter

Type

Description

Name

String

Name of the collection to be created

Options

Document

(Optional) Specify options about memory size and indexing

 

Options parameter is optional, so you need to specify only name of the collection. Following is the list of options you can use:

Field

Type

Description

 

 

capped

 

 

Boolean

(Optional) If true, enables a capped collection. Capped collection is a collection fixed size collecction that automatically overwrites its oldest entries when it reaches its maximum size. If you specify true, you need to specify size parameter also.

autoIndexID

Boolean

(Optional) If true, automatically create index on _id field.s Default value is false.

 

size

 

number

(Optional) Specifies a maximum size in bytes for a capped collection. If If capped is true, then you need to specify this field also.

max

number

(Optional) Specifies the maximum number of documents allowed in the capped collection.

 










While inserting the document, MongoDB first checks size field of capped collection, then it checks max field

Basic syntax of createCollection() method without options is as follows

>use test switched to db test

>db.createCollection("mycollection")

{ "ok" : 1 }

You can check the created collection by using the command show collections

>show collections

mycollection

system.indexes

 

4.Creating collection with options before inserting the documents and drop the collection created.

In mongodb you don't need to create collection. MongoDB creates collection automatically, when you insert some document.


>db.tutorialspoint.insert({"name" : "tutorialspoint"})

>show collections mycol mycollection

 system.indexes

 tutorialspoint


> 

MongoDB's db.collection.drop() is used to drop a collection from the database.

Syntax:

Basic syntax of drop() command is as follows

First, check the available collections into your database mydb

>use mydb

switched to db mydb

>show collections

 mycol mycollection

 system.indexes

 tutorialspoint

> 

Now drop the collection with the name mycollection

>db.tutorialpoint.drop()

true

> 

Again check the list of collections into database

 

>show collections

 mycol 

system

.indexes

 tutorialspoint

> 

  

5.MogoDB Insert Document

a.Inserting single document

The insert() Method

To insert data into MongoDB collection, you need to use MongoDB's insert() or save()method

 

Example :

db.post.insert([

{

title: 'MongoDB Overview',

description: 'MongoDB is no sql database',

by: 'tutorials point',

url: 'http://www.tutorialspoint.com',

tags: ['mongodb', 'database', 'NoSQL'],

likes: 100

},

{

title: 'NoSQL Database',

description: 'NoSQL database doesnt have tables',

by: 'tutorials point',

url: 'http://www.tutorialspoint.com',

tags: ['mongodb', 'database', 'NoSQL'],

likes: 20,

comments: [

{

user:'user1',

message: 'My first comment',

dateCreated: new Date(2013,11,10,2,35),

like: 0

}

]

}

])

 

To insert the document you can use db.post.save(document) also. If you don't specify _id in the document

then save() method will work same as insert() method. If you specify _id then it will replace whole data of

document containing _id as specified in save() method.

 

 

b) Inserting Multiple Documents

You can insert multiple documents into an existing collection in MongoDB using the insertMany() method.

Syntax

db.coll.insert(docArray)

Where,

  • db is the database.

  • coll is the collection (name) in which you want to insert the document

Example

> use myDatabase()
switched to db myDatabase()
> db.createCollection(sample)
{ "ok" : 1 }
> db.test.insert([{name:"Ram", age:26, city:"Mumbai"}, {name:"Roja", age:28,
city:"Hyderabad"}, {name:"Ramani", age:35, city:"Delhi"}])
BulkWriteResult({
   "writeErrors" : [ ],
   "writeConcernErrors" : [ ],
   "nInserted" : 3,
   "nUpserted" : 0,
   "nMatched" : 0,
   "nModified" : 0,
   "nRemoved" : 0,
   "upserted" : [ ]
})


Or

To insert multiple documents we can use insertMany() - which takes an array of documents as parameter. When executed, it returns multiple ids for each document in the array. To drop the collection, use drop() command. Sometimes, when doing bulk inserts - we may insert duplicate values. Specifically, if we try to insert duplicate _ids, we'll get the duplicate key error:

creating new collection

>db.create("startup")
{ ok: 1 }
inserting many documents

>db.startup.insertMany(
  [
  {_id:"id1", name:"Uber"},
  {_id:"id2", name:"Airbnb"},
  {_id:"id4", name:"Ola"},
  ]
  );


>db.startup.insertMany(
  [
  {_id:"id4", name:"Uber"},
  {_id:"id5", name:"Airbnb"},
  {_id:"id6", name:"Ola"},
  ]
  );

showing all documents

db.startup.find()
{ _id: 'id1', name: 'Uber' }
{ _id: 'id2', name: 'Airbnb' }
{ _id: 'id4', name: 'Uber' }
{ _id: 'id5', name: 'Airbnb' }
{ _id: 'id6', name: 'Ola' }

6.Querying all the documents in json format and Querying based on the criteria. 
creating new collection

>db.create("startupnew")
{ ok: 1 }
inserting many documents

>db.startupnew.insertMany(
  [
  {_id:"id1", name:"Uber"},
  {_id:"id2", name:"Airbnb"},
  {_id:"id4", name:"Ola"},
  ]
  );


>db.startupnew.insertMany(
  [
  {_id:"id4", name:"Uber"},
  {_id:"id5", name:"Airbnb"},
  {_id:"id6", name:"Ola"},
  ]
  );

showing all documents

db.startupnew.find()
{ _id: 'id1', name: 'Uber' }
{ _id: 'id2', name: 'Airbnb' }
{ _id: 'id4', name: 'Uber' }
{ _id: 'id5', name: 'Airbnb' }
{ _id: 'id6', name: 'Ola' }

Qureying whose name is Uber

>db.startupnew.find({name:"Uber"})
{ _id: 'id1', name: 'Uber' }
{ _id: 'id4', name: 'Uber' }





7. MongoDB update document 
	a. Using update() method. 
	b. Using save() method. 

creating new collection

>db.createCollection("startup1")
{ ok: 1 }

inserting many documents

>db.startup1.insertMany(
  [
  {_id:"id1", name:"Uber"},
  {_id:"id2", name:"Airbnb"},
  {_id:"id3", name:"Ola"},
  {_id:"id4", name:"Amazon"},
  {_id:"id5", name:"Microsoft"},
  {_id:"id6", name:"Google"},
  ]

);

showing all documents

>db.startup1.find()

  {_id:"id1", name:"Uber"}
  {_id:"id2", name:"Airbnb"}
  {_id:"id3", name:"Ola"}
  {_id:"id4", name:"Amazon"}
  {_id:"id5", name:"Microsoft"}
  {_id:"id6", name:"Google"}

The update() method updates values in the existing document.


By default mongodb will update only single document, to update multiple you need to set a paramter 'multi' to true.

>db.startup1.update({'name':'Ola'},{$set:{'name':'New MongoDB By RVS'}},{multi:true})


The save() method replaces the existing document with the new document passed in save() method

>db.startup1.save(
{
"_id" : "id6", "name":"MangoDB  Document Replacing "
}
)


showing all documents after updation

>db.startup1.find()

  {_id:"id1", name:"Uber"}
  {_id:"id2", name:"Airbnb"}
  {_id:"id3", name:"Ola"}
  {_id:"id4", name:"Amazon"}
  {_id:"id5", name:"Microsoft"}
  {_id:"id6", name:"MangoDB  Document Replacing "}


8. MongoDB delete document from a collection.

a. Using remove() method.

b. Remove only one document matching your criteria

c. Remove all documents


MongoDB's remove() method is used to remove document from the collection.

remove() method accepts two parameters. One is deletion criteria and second is

justOne flag

1. deletion criteria : (Optional) deletion criteria according to documents will be removed.

2. justOne : (Optional) if set to true or 1, then remove only one document.


Syntax:

Basic syntax of remove() method is as follows

>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)

Example

creating new collection “startupnew”

>db.createCollection("startupnew")
{ ok: 1 }
inserting many documents 
 >db.startupnew.insertMany(
  [
  {_id:"id1", name:"Uber"},
  {_id:"id2", name:"Airbnb"},
  {_id:"id4", name:"Ola"},
  ]
  );
 
>db.startupnew.insertMany(
  [
  {_id:"id4", name:"Uber"},
  {_id:"id5", name:"Airbnb"},
  {_id:"id6", name:"Ola"},
  ]
  );
 
showing all documents
db.startupnew.find()

{ _id: 'id1', name: 'Uber' }
{ _id: 'id2', name: 'Airbnb' }
{ _id: 'id4', name: 'Uber' }
{ _id: 'id5', name: 'Airbnb' }
{ _id: 'id6', name: 'Ola' }

Remove only one document matching your criteria :

>db.startupnew.remove({'name':'Ola'})

showing all documents after removing  “Ola”

db.startupnew.find()
{ _id: 'id1', name: 'Uber' }
{ _id: 'id2', name: 'Airbnb' }
{ _id: 'id4', name: 'Uber' }
{ _id: 'id5', name: 'Airbnb' }


Following example will remove all the documents whose title is 'MongoDB Overview'

Remove All documents :

If you don't specify deletion criteria, then mongodb will delete whole documents from the collection.

This is equivalent of SQL's truncate command.

>db.startupnew.remove()

After removing all documents

>db.mycol.find()

> 





 

 


9. MongoDB Projection

In mongodb projection meaning is selecting only necessary data rather than selecting whole of the data of a

document. If a document has 5 fields and you need to show only 3, then select only 3 fields from them.

The find() Method :


MongoDB's find() method accepts second optional parameter that is list of fields that you want to retrieve. In MongoDB when you execute find() method, then it displays all fields of a document. To limit this you need to set list of fields with value 1 or 0. 1 is used to show the filed while 0 is used to hide the field.

Syntax:

Basic syntax of find() method

with projection is as follows

>db.COLLECTION_NAME.find({},{KEY:1})

Example :

creating new collection “startupnew”

>db.createCollection("startupnew")
{ ok: 1 }
Inserting many documents 
>db.startupnew.insertMany(
  [
  {_id:"id1", name:"Uber"},
  {_id:"id2", name:"Airbnb"},
  {_id:"id4", name:"Ola"},
  ]
  );

showing all documents in startupnew

db.startupnew.find()
{ _id: 'id1', name: 'Uber' }
{ _id: 'id2', name: 'Airbnb' }
{ _id: 'id4', name: 'Ola' }

Following example will display the title of the document while quering the document.

>db.startupnew.find({},{"name":1,_id:0})

{  name: 'Uber' }
{  name: 'Airbnb' }
{  name: 'Ola' }

> 

Please note _id field is always displayed while executing find() method, if you don't want this field,

then you need to set it as 0


 


10. limit() ,skip(), sort() methods in MongoDB

The limit() Method :

To limit the records in MongoDB, you need to use limit() method. limit() method accepts one number type argument, which is number of documents that you want to displayed. Syntax: Basic syntax of limit() method is as follows

>db.COLLECTION_NAME.find().limit(NUMBER)

creating new collection “startupnew”
 
>db. createCollection ("startupnew")
{ ok: 1 }
 
inserting many documents
 
>db.startupnew.insertMany(
  [
  {_id:"id1", name:"Uber"},
  {_id:"id2", name:"Airbnb"},
  {_id:"id4", name:"Ola"},
  ]
  );

 

showing all documents in startupnew
 
db.startupnew.find()
 
{ _id: 'id1', name: 'Uber' }
{ _id: 'id2', name: 'Airbnb' }
{ _id: 'id4', name: 'Ola' }

 

Following example will display only 2 documents while quering the document.

>db.startupnew.find({},{"name":1,_id:0}).limit(2)

{ _id: 'id1', name: 'Uber' }

{ _id: 'id2', name: 'Airbnb' }

> 

If you don't specify number argument in limit() method then it will display all documents from the collection.

The Skip() method:

Apart from limit() method there is one more method skip() which also accepts number type argument and used to skip number of documents.

Syntax:

Basic syntax of skip() method is as follows..

>db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)

 Example:

 Following example will only display only second document.

>db.startupnew.find({},{"name":1,_id:0}).limit(1).skip(1)

{ _id: 'id2', name: 'Airbnb' }
 

 >

Please note default value in skip() method is 0

The sort() Method :

To sort documents in MongoDB, you need to use sort() method. sort() method accepts a document containing list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

 Syntax:

Basic syntax of sort() method is as follows

>db.COLLECTION_NAME.find().sort({KEY:1})

Example :

 Consider the collection startupnew  has the following data

{ _id: 'id1', name: 'Uber' }
{ _id: 'id2', name: 'Airbnb' }
{ _id: 'id4', name: 'Ola' }

 

Following example will display the documents sorted by name in descending order.

>db.startupnew.find({},{"name":1,_id:0}).sort({"name":-1})

{ _id: 'id1', name: 'Uber' }
{ _id: 'id4', name: 'Ola' }
{ _id: 'id2', name: 'Airbnb' }
 

Please note if you don't specify the sorting preference, then sort() method will display documents in ascending order.

11. MongoDB indexing

            a. Create index in MongoDB

b. Finding the indexes in a collection

c. Drop indexes in a collection

d. Drop all the indexes 

 

Indexes support the efficient resolution of queries. Without indexes, MongoDB must scan every document of a collection to select those documents that match the query statement. This scan is highly inefficient and require the mongod to process a large volume of data.

The ensureIndex() Method

 

To create an index you need to use ensureIndex() method of mongodb.

 

Syntax:

 Basic syntax of ensureIndex() method is as follows()

 >db.COLLECTION_NAME.ensureIndex({KEY:1})

 Here key is the name of filed on which you want to create index and 1 is for ascending order. To create index in descending order you need to use -1.

 Example :-

creating new collection “startupnew”
 >db. createCollection ("startupnew")
{ ok: 1 }
 inserting many documents
 >db.startupnew.insertMany(
  [
  {_id:"id1", name:"Uber",description:”US”},
  {_id:"id2", name:"Airbnb",description,”IND”},
  {_id:"id4", name:"Ola",description:”IND”},
  ]
  );
showing all documents in startupnew
 
db.startupnew.find()
 
  {_id:"id1", name:"Uber",description:”US”},
  {_id:"id2", name:"Airbnb",description,”IND”},
  {_id:"id4", name:"Ola",description:”IND”},

 

 

 

>db.startupnew.ensureIndex({"name":1})

                        Or

db.startupnew.createIndex(

{name: 1},

{name: "cab index"}

)

In ensureIndex() method you can pass multiple fields, to create index on multiple fields.

 >db. startupnew.ensureIndex({"name":1,"description":-1})

> ensureIndex()  method also accepts list of options (which are optional), whose list is given below:


b)Finding indexes

 You can find all the available indexes in a MongoDB collection by using the getIndexes method. This will return all the indexes in a specific collection.

 db.startupnew.getIndexes()

 c) Dropping indexes

To delete an index from a collection, use the dropIndex method while specifying the index name to be dropped.

 db.startupnew.dropIndex("cab  index")

 d) Dropping all indexes

The dropIndexes command can also drop all the indexes excluding the default _id index.

db.startupnew.dropIndexes()

 

 

 

 

 

 





No comments:

Post a Comment