Vous êtes sur la page 1sur 13

MongoDB

Its Document Orientended Database.

its supports JSON.

Its No-Sql database.

We can insert JSON object into MongoDB.

We can even perform CURD operations on JSON.

Its light weight database

e.g when compared to Oracle,MySql,Sql Server

It follows Client/Server Architecture.

It follows MongoDB protocol.

Its default port no : 27071

Its prerequestite is to understand MongoDB.

JSON
It stands Java Script Object Notation.

Its used to transfer data over the Network.

Parsing of JSON is easy.

JSON is light weight compared toXML.

Syntax.

1. Object {}
2. Array []
3. Data {Key:Value} pair. {Key:Value,Key:Value...} pairs.
4. Array of Object [{Key:Value},{Key:Value}..]
5. Script tag <script></script> to include JavaScript to web page.
6. Console class is used to display log messages on browser console.(ctrl+shift+i).
7. Document is the class used to display data on webpage.

Ex 1:

Create an JSON Object by using following variable.


@data

JSON keys and values are:

Keys

@sub_one

@sub_two

@sub_three

Values

@Angular7

@NodeJS

@MongoDB

Index.html

<html>

<script>

Var
data={“sub_one”:”Angular7”,”sub_two”:”NodeJS”,”sub_three”:”MongoDB”};

Document.write(data.sub_one+”...”+data.sub_two+”...”+data.sub_three);

</script>

</html>

Ex-2:

Create JSON array by using following data

1. data
2. JSON array has 5 Objects. Each JSON Object has following
p_id: value varies from 111 to 555
p_name:value varies from p_one to p_five
p_cost:value varies from 10000 to 50000.

Index.html

<html>
<script>

Var data=[ {“p_id”:111,”p_name”:”p_one”,”p_cost”:10000},

{“p_id”:222,”p_name”:”p_two”,”p_cost”:20000},

{“p_id”:333,”p_name”:”p_three”,”p_cost”:30000},

{“p_id”:444,”p_name”:”p_four”,”p_cost”:40000},

{“p_id”:555,”p_name”:”p_five”,”p_cost”:50000}];

For(var i=0;i<data.length;i++)

Var obj=data[i];

Document.write(obj.p_id+”...”+obj.p_name+”...”+obj.p_cost);

</script>

</html>

Ex 3:

Create JSON Object by using following variable.

@Data

This outer JSON Object(data) has inner Object(inner object).

Inner Object has following key

@sub_one

Value is

@mongodb

<html>

<script>

Var data={“inner_obj”:{“sub_one”:”mongodb}};

Document.write(data.inner_obj.sub_one);
</script>

</html>

Ex 4:

Read the data from following URL:

https://www.w3schools.com/angular/customers.php

Note: https://www.jsonviewer.stack.hu

<html>

<script>

Var data={ "records":[ {"Name":"Alfreds


Futterkiste","City":"Berlin","Country":"Germany"}, {"Name":"Ana Trujillo Emparedados y
helados","City":"México D.F.","Country":"Mexico"}, {"Name":"Antonio Moreno
Taquería","City":"México D.F.","Country":"Mexico"}, {"Name":"Around the
Horn","City":"London","Country":"UK"}, {"Name":"B's
Beverages","City":"London","Country":"UK"}, {"Name":"Berglunds
snabbköp","City":"Luleå","Country":"Sweden"}, {"Name":"Blauer See
Delikatessen","City":"Mannheim","Country":"Germany"}, {"Name":"Blondel père et
fils","City":"Strasbourg","Country":"France"}, {"Name":"Bólido Comidas
preparadas","City":"Madrid","Country":"Spain"}, {"Name":"Bon
app'","City":"Marseille","Country":"France"}, {"Name":"Bottom-Dollar
Marketse","City":"Tsawassen","Country":"Canada"}, {"Name":"Cactus Comidas para
llevar","City":"Buenos Aires","Country":"Argentina"}, {"Name":"Centro comercial
Moctezuma","City":"México D.F.","Country":"Mexico"}, {"Name":"Chop-suey
Chinese","City":"Bern","Country":"Switzerland"}, {"Name":"Comércio
Mineiro","City":"São Paulo","Country":"Brazil"} ] };

For(var i=0;i<data.records.length;i++)

Var obj=data.records[i];

Document.write(obj.name+”…”+obj.city+”…”+obj.country+”<br>”);

};

</script>

</html>
Ex 5:

Read the data from URL

https://www.restcountries.eu/rest/v2/all

var data=
[{"name":"Afghanistan","topLevelDomain":[".af"],"alpha2Code":"AF","alpha3Code":"AFG"
,"callingCodes":["93"],"capital":"Kabul","altSpellings":["AF","Afġānistān"],"region":"Asia",
"subregion":"Southern
Asia","population":27657145,"latlng":[33.0,65.0],"demonym":"Afghan","area":652230.0,"gi
ni":27.8,"timezones":["UTC+04:30"],"borders":["IRN","PAK","TKM","UZB","TJK","CHN"
],"nativeName":"‫"افغانستان‬,"numericCode":"004","currencies":[{"code":"AFN","name":"Afgh
an
afghani","symbol":"؋"}],"languages":[{"iso639_1":"ps","iso639_2":"pus","name":"Pashto","n
ativeName":"‫}"پښتو‬,{"iso639_1":"uz","iso639_2":"uzb","name":"Uzbek","nativeName":"Oʻz
bek"},{"iso639_1":"tk","iso639_2":"tuk","name":"Turkmen","nativeName":"Türkmen"}],"tr
anslations":{"de":"Afghanistan","es":"Afganistán","fr":"Afghanistan","ja":"アフガニスタン
","it":"Afghanistan","br":"Afeganistão","pt":"Afeganistão","nl":"Afghanistan","hr":"Afganist
an","fa":"‫}"افغانستان‬,"flag":"https://restcountries.eu/data/afg.svg","regionalBlocs":[{"acronym"
:"SAARC","name":"South Asian Association for Regional
Cooperation","otherAcronyms":[],"otherNames":[]}],"cioc":"AFG"}];

for(var i=0;i<data.length;i++)

Var obj=data[i];

Document.write(obj.name+”…”+obj.capital+”…”+obj.currencies[0].code+”…”+”<img
width=’50px’ height=’50px’ src=”+obj.flag+”><br>”);

};

</script>

</html>

Ex no: 6

Create the JSON Object by using following variable

@data

JSON Keys are

@sub_one

@sub_two
@sub_three

JSON Values are following named functions

Fun_one() return “mongodb”

Fun_two() return “couchdb”

Fun_three() return “robodb”

<html>
<script>

var data={sub_one:fun_one(),sub_two:fun_two(),sub_three:fun_three()};

function fun_one(){
return "mongodb";
}

function fun_two(){
return "casndradb";
}

function fun_three(){
return "robodb";
}

document.write(data.sub_one+"<br>"+data.sub_two+"<br>"+data.sub_three);
</script>
</html>

Ex no: 7

<html>
<script>
function fun_one(){
return "welcome";
};

document.write(fun_one+"<br>"+fun_one());
</script>
</html>

Ex no: 8

<html>
<script>
function fun_one(){
return fun_two;
}

function fun_two(){
return "fun_two";
}

document.write(fun_one());
</script>
</html>

Ex no: 9

Create JSON Object by using following variables

JSON keys are

@mongodb

@couchdb

@robodb

@casandradb

JSON values are ‘named functions’

@mongodb : return “mongodb”

@couchdb : return “couchdb”

@robodb : return “robodb”

@casandradb : return “casandradb”

<html>
<script>

var data={
mongodb:mongodb,
couchdb:couchdb,
robodb:robodb(),
casandradb:casandradb
};

function mongodb(){
return "mongodb";
};
function couchdb(){
return "couchdb";
};

function robodb(){
return "robodb";
};

function casandradb(){
return "casandradb";
}

document.write(data.mongodb+"<br>"+data.couchdb()+"<br>"+data.mongodb+"<br>"+d
ata.robodb+"<br>"+data.casandradb);
</script>
</html>

Ex no:10

<html>
<script>
var data=()=>{return "hello"};
document.write(data+"<br>"+data());
</script>
</html>

Ex no: 11

<html>
<script>
var data={
oracle:()=>{return "oracle"},
mysql:()=>{return "mysql"},
mssql:()=>{return "mssql"},
mongodb:()=>{return "mongodb"},
};
document.write(data.oracle+"<br>"+data.mysql()+"<br>"+data.mssql+"<br>"+data.m
ongodb);
</script>
</html>

Installation of MongoDB
-----------------------
1) download and install mongodb
website : https://www.mongodb.com/download-center/community
file : mongodb-win32-x86_64-2008plus-ssl-4.0.5-signed.msi
2) create the following directory structure
C:/data/db
3) set the path environmental variable
path = C:\Program Files\MongoDB\Server\4.0\bin
************************
Basic MongoDB Operations
************************
1) start the server
> mongod
- mongodb follows client server architecture.
- mongo server running on port no.27017
- mongodb default port no.27017
- mongodb by default follows the "mongodb" protocol.
- if we run above command automatically mongodb server will start.
2) Assign the custom port no.
> mongod --port 1234
- automatically mongo server running on custom port no.1234
3) shut down the server
> ctrl+c
- automatically server will shut down.
4) assigning the custom backup path
> mongod --dbpath C:\Users\india\Desktop\hello
- automatically "hello" directory as backup path for mongodb.
5) custom directory path and port no.
> mongod --dbpath C:\Users\india\Desktop\hello --port 1234
- automatically "hello" is backup path and 1234 as port no.
6) connecting to server as client
> mongo
- automatically we can connect to server.
7) show the available databases
> show dbs;
- it will show the available databases.
- following databases are default databases in mongodb
1) admin
2) config
3) local
8) create and switch to database.
> use testdb;
- automatically "testdb" will be created and switches also
9) create the collection (table)
> db.createCollection("products");
- automatically "products" collection will be created.
- collection means we can treate like table.
10) insert the documents.
- json objects we can call documents in mongodb
> db.products.insert({"p_id":111,"p_name":"p_one","p_cost":10000});
- automatically document will be inserted in products collection.
11) insert the multiple documents
> db.products.insertMany([{"p_id":111,"p_name":"product_one","p_cost":100000},
{"p_id":111,"p_name":"pone","p_cost":1000000}]);
- automatically multiple documents will be inserted in products collection
12) fetch the documents from products collection.
> db.products.find();
- it will show available documents in products collection.
- "mongodb" by default generates primary key in the form of a "_id".
13) fetch and display the data in the form of readable format
> db.products.find().pretty();
14) display the data based on condition
> db.products.find({"p_id":111}).pretty();
- it will show all the matching records of "111".
15) show particular fields.
> db.products.find({"p_id":111},{"p_name":1,
"p_id":1,
"p_cost":1,
"_id":0}).pretty();
0 Means Hiding the Field.
1 Means Showing the Field
16) update single document
> db.products.updateOne({"p_id":111},
{$set:{"p_name":"hello",
"p_Cost":100}});
- automatically first occurance of "111" record updated
17) update the all matching records
> db.products.updateMany({"p_id":111},
{$set:{"p_name":"hi",
"p_cost":200}});
- automatically all the matching records will be updated.
18) delete the first occurance record from collection.
> db.products.deleteOne({"p_id":111});
19) delete the multiple occurances
> db.products.deleteMany({"p_id":111});
20) remove all the documents from collection.
> db.products.remove({});
21) remove the collection
> db.products.drop();
22) drop the database
> db.dropDatabase();
MongoDB with NodeJS
-------------------
- "mongodb" is the module given by node js.

- "mongodb" module used to connect to "Node Server".

- the stable version of mongodb module is "2.2.32".

- we will download "mongodb" module by using


"yarn" packaging manager.

- "mongodb" module downloads to "node_modules" folder.

Steps to implement the Application


----------------------------------
Step 1.
make the database ready.
start the server
> mongod

connect to server
> mongo

create and switch to database


> use my_db;

create the collection


> db.createCollection("products");
insert documents

> db.products.insertMany([
{"p_id":111,"p_name":"p_one","p_cost":10000},
{"p_id":222,"p_name":"p_two","p_cost":20000},
{"p_id":333,"p_name":"p_three","p_cost":30000},
{"p_id":444,"p_name":"p_four","p_cost":40000},
{"p_id":555,"p_name":"p_five","p_cost":50000}
]);

fetch the documents


> db.products.find();
***************************************
host : localhost
protocol: mongodb
port : 27017
database: my_db
collection: products
***************************************
Step 2.
download and install NodeJS.
website : https://nodejs.org/en/download/

file : node-v10.15.0-x64.msi

Step 3.
download and install Git.
website : https://git-scm.com/download/win

file : Git-2.20.1-64-bit.exe

Step 4.
install "yarn" packaging manager
> npm install -g yarn@latest

Step 5.
download the following node modules
1) express

2) mongodb@2.2.32

- "express" module used to provide the communication between Node Server to


Databases.

- "mongodb@2.2.32" module used to interact with the mongodb database.

- we will download above modules by using "yarn" tool.

- all the above modules downloads to "node_modules" folder in current path

> yarn add express mongodb@2.2.32 --save

Step 6.
implement the node application to fetch the data from mongodb database.
*************************
ExpressJS
server.js
*************************
Step 7.
Start the Node Server
> node server

Step 8.
Test the following Rest API By Using "Postman".
=> http://localhost:8080/demo

Vous aimerez peut-être aussi