You are on page 1of 9

NPMs required:-

To connect to mongodb:-

const db =
'mongodb+srv://NamanKothari:namankothari@cluster0.ssrsv38.mongodb.net/
cardbase?retryWrites=true&w=majority'

//write your own username and password instead of NamanKothari:namankothari


and writeyour databases name instead of cardbase.

mongoose.connect(db, {
  useNewUrlParser: true, //we do this in order to not receive the deprecation warnings
  useCreateIndex: true,
  useUnifiedTopology: true,
  useFindAndModify: false
})
.then(() => {
  console.log("connection successful");
}).catch((err) => console.log("connection failed!"));

Recommended:-

1- not to use db.student.insert({name: “admin”})  instead use createcollection and insert


separately so you can also give the collection(table) different parameters such as restriction of
capping.

2- mongo has 2 types of documents one is relational and second is embedded  embedded is
always recommended as it will help you smoothly scale up and down.

Features:-

Schema free

Single document model

Why Mongo db?

Notion of Documents nested in sub documents – very flexible and expressive.

Characteristic:-

1-General purpose database- serves heterogenous loads and multiple purpose applications

2-MAJOR DIFF - Document oriented approach- non defined attributes that can be modified
anytime
3- scalability and load balancing- can be scaled both ways vertically and mostly used horizontally and
using sharding can share load between different instances and achieves both Read and write
scalabilities.

Working:-

Documents store data with the help of key value pairs.

Data is stored in bson format

Mongodb makes provision for nested data- this makes fetching data very easy compared to other
databases.

GK:-

General knowledge as to why create a path- “so that you can access that file and open it from the
command prompt and don’t always have to go through the bin folder to execute that file”

 One would not have to have a schema before they start building a database and this
provides flexibility as one is creating the database.
 Mongo is the client that will connect to the server (Mongod)\
 Everytime you create a table mongodb associates an id to every document you create which
is shown when u use the find function and shows up like
“’_id’:objected(“256554454365645e4”)”

Called:-

Table  collection

Db  db

Row  document

COMMANDS:-

1-Show dbs;  show all databases

* doesn’t show a database which doesn’t have even one record in it.

2- Use cardbase  creates a database named cardbase and shifts to it

3- Db;  shows the db u currently are in

4- Db.createCollection(‘democollection’)  creates a table named democollection

(after this the database should be listed)


5- db.student.insert({name: ‘naman’})  Not only does it create a new table called STUDENT but
also inserts a column named name and with the value of naman

6- show collections;  displays all the tables you have

7- db.student.find()  lists all the column and its values that you have created. For eg for now it will
show {“name”: “naman”}

* if you use the find function on a table which has no columns added then it won’t show any
result(ob)

8- db.createcollection(‘tablename’, {capped: true, size: 5242880, max:5})  create a table named


“tablename” and limit/restrict it to max of 5 documents as well as 5mb space, if the table gets 3
documents with >5mb space then it wont let the user create another document or add more info.
Similar with 5 document case.

9- db.student.insert({name:”naman”, idno:”56”, courses:{coursename:”coding”,duration:”3 years”},


address: {city: “mum”, state:”mha”, country:”ind”}})  creates a table named student and enters
column columns such as name,courses,idno,address and inserts values inside the rows such as
coursename, duration,city,state and the values are coding,3 years, mum, etc.

The option for entering data in BULK:-

Var empdetails = [{empname:”naman”, empsurname:”kothari”},


{empname:”parshva”,empsurname:”kothari”},{empname:”paras”, empsurname:”kothari”}]

Db.empofstylabs.insert(empdetails);  both of these commands one after the other will add the
details of the empyolee stored in empdetails into the newly created table empofstylabs.

10- db.empofstylabs.update({empname:”namrata”}, {$set:{“empname”:”mummy”}})  this will


update the empname of namrata in the table empofstylabs to mummy.

* keep this in mind that THIS update will only change one value of empname-namrata to
empname-mummy. If there are multiple namrata’s then only the first one from the top of the table
will change and NOT ALL!

11- db.empofstylabs.update({empname:”namrata”}, {$set:{“empname”:”mummy”}},{multi:true}) 


this will update all the values of namrata to mummy in the entire database. For Multiple updates!

12- db.empofstylabs.update({empname:”namrata”}, {$set:{“empname”:”mummy”}},{upsert:true})


 this will try to find the empname- namrata and change it to mummy IF FOUND, if it isn’t found
then it will just simply insert empname:mummy in a new row

13- db.empofstylabs.remove({“empname”:”naman”})  will delete all the employe in the collection


who have empname as naman and not only one. * removes all things that match that criteria in
the entire collection.

Conditions:-

14-db.empofstylabs.find({“empname”:”naman”});  helps you find a particular record in that


collection

15- db.empofstylabs.find().limit(2);  will show you only 2 records instead of howmany ever you
have in your collection and those 2 will be from the top of the collection.
16- db.empofstylabs.find().sort({empname:-1})  shows you the data in descending order that is z
letter in empname will show first and a letter in empname will show last. IF you change the condition
to {empname:1}  then it will show u therecords in the collection in ascending order.

17- to access embedded records –refer the 9th ^ command above in which I have embedded record
collection. In such a case to refer to the embedded records in that collection you can do:-

Db.student.find({“courses.coursename”:”coding”})  this will provide you the record with only that
embedded coursename. 👆 notice the use of .(dot) here to access embedded record.

18- db.empofstylabs.find({empid:{$gt:1}})  will display us all the records that have an empid of
GREATER THAN($gt) 1.

19 - db.empofstylabs.find({empid:{$lt:5}})  will display us all the records that have an empid of


LOWER THAN($lt) 5.

20-db.empofstylabs.find({empid: {$in:[3,6]}})  will display to you the records 3 and 6

INDEXING:- IMP

21- db.empofstylabs.explain("executionStats").find({empname:"qa"})  EXECUTIONSTATS is a


predefined functions which will tell us that when the find function was run for empname:”qa” –
what the query plan was and details about it. It scans all the documents that are present in that
collection and then replies with the result. – mainly notice the totalnumberofdocsexamined.

22- db.empofstylabs.getIndexes() -> predefined functions that tells us the index which is by default
applied on the _id of the document.

Which of the properties are required to get indexes

MONGODB’s advantage is that it SUPPORTS multi-column indexes.

To apply indexes in your own properties from the by default _id indexes:-

23- db.empofstylabs.createIndex({“empname”:1})  creates an index in ascending order since you


have mentioned “:1” 👆- the property on which you would like to apply the
indexing and if in ascending order or descending order. If ascending then write 1 otherwise write -1.

In result it will tell us number of indexes applied on properties and how many properties have those
index numbers after this function being run.

HOW DOES INDEXING HELPS:-

When you search for something it usually check through everything in that collection from every
properties and their value but once yu apply indexing it only checks for indexing of that collections

24- db.empofsty;abs.dropIndex(“empname_1”)  drops the index of the property that you have
mentioned you can do this with any column. 👆 notice the _1 here that is necessary to mention
in order to drop an index as it was assigned, as in this case it was assigned as:-

Key {

“empname”:1  empname_1
}

AGGREGEATION:-

Well known functionalities of aggregation are:-

1- $project  select specific fields

2- $match  filtering of the operations

3- $group  does actual aggregation

4- $sort  sorts the documents

1.1db.student.aggregate([{"$project":{StudentName:1,Section:1,Marks:1}}]);

 👆(1,0) decides if it should be


displayed or not if 0 then it wont and if 1 then it will.

 selects the field specified and displays ONLY those fields that we have selected(by
keeping its number 1).

1.2 db.student.aggregate([{"$project":{StudentName:1,Section:1,Marks:1,_id:0}}]);  just


another example of $project where id is not being shown.

2.1db.student.aggregate([{“$match”: {“Section”:”A”}}])  filters out others and only


displays the records which have section as A in them.

2.2db.student.aggregate([{$match:{ $and: [{"Section":" A "},{Marks: {"$gt":80}}]}}]);  using


the AND OPERATOR with the filtering function (match) to filter out two things at once: the
section as well as the marks of the student in that section.

2.3 USING BOTH PROJECT AND MATCH:-

db.student.aggregate([{$match:{"Section":" A "}},{"$project":{StudentName:1,Section:1,Marks:1}}]);
 not only filters and provides only those records which have section A in them but also displays
only the studentname, section and marks of those records.

3.1 db.student.aggregate([{"$group" : { "_id" : { "Section" : "$Section" } ,"TotalMarks" : { "$sum" :


"$Marks" } } } ] );  this groups all the data together such as adds marks sectional wise and displays
them. Groups the same sections such as “A” with “A” and adds the marks in section A with the other
marks present in section A and displays it as totalmarks.

**!!  ID always has to be mentioned when Grouping is done otherwise it won’t works and in this
case when using javascript you have to be careful cause it is CASE SENSITIVE.

3.2 USING BOTH MATCH AND GROUP:-


db.student.aggregate([{"$match": {Section: " A "}},{"$group" : { "_id" : { "Section" :
"$Section" } ,"TotalMarks" : { "$sum" : "$Marks" } } } ] );  this does the same thing as above in 3.1
except that it filters the choices and only displays the group of section A and not others.

3.3 db.student.aggregate([{"$group":{"_id":{"Section":"$Section"},"TotalMarks":
{"$sum":"$Marks"},"Count":{"$sum":1},"Average":{"$avg":"$Marks"}}}]);  performs multiple
groups in which it groups the sections according to their sum of their marks as well as displays their
average.

MONGODB ATLAS:-

REPLICATION:-

Master and Slaves:-

👆(1) 👆(multiple)

Why is it used:- ***

If one node fails then the data can automatically be taken from another node – the major
point.

** You can only insert record inside your primary node, you can NEVER inert records in the
secondary node.

FIRST STEP- Network Access (keep it 0.0.0.0 it make it lsn to all requests) – to select the ip address
you want It to lsn to.

SECOND STEP:-database access (add a new user)

Third step- create a database inside connections on homepage cluster (click on connections)

Fourth step- connectto the database by clicking on connect on the homepage of cluster.

EXTRAS:-

1 - CONFIG.ENV –

Create a config.env file in order to secure your database username and password that you have to
mention in order to connect nodejs to it.

Create the config.env file by writing in terminal :- “ type null > config.env ”

Create a variable in config.env file to store whatever data you do not want other to see of your
project. **The variable can only be in ALL CAPS.

Currently for my mongodb it is like this:-


DATABASE=mongodb+srv://NamanKothari:namankothari@cluster0.ssrsv38.mongodb.net/cardbase?
retryWrites=true&w=majority

PORT = 3000

** to access the port and database in the config.env into the project you will have to give the path
along with the:-

dotenv.config({path:"../config.env"})
const port = process.env.PORT;
const database = process.env.DATABASE;

2- Gitignore- you know its purpose just don’t forget to add config.env to it.

To create a gitignore file type in cmd :- “ echo “” > .gitignore”

AFTER CONNECTING, CREATING A SCHEMA:-

Use the npm modules’ function “ new mongoose.Schema({})” and create a collection by
“mongoose.model(“User”, userSchema)”  user being the collection name and userschema the
variable in which you store the schema.

For Eg:-

import mongoose from "mongoose";

const userSchema = new mongoose.Schema({


    id: {
        type: Int,
        required: true
    },
    name: {
        type: String,
        required: true
    },
    email:{
        type: String,
        required: true
    },
    joined: {
        type: TimeRanges,
        required: true
    }
})
const User = mongoose.model("User", userSchema);
export default User;

after schema putting the schema to work in the app.post(/register) :-


user.findOne({email: email}).then() ……

{ " _id " : ObjectId ( " 60ad0223e47de45e5e523e21 " ) , " StudentName " : " Vijay " , " Section " : " A "
,“Marks " : 70 , " Subject " : [ " Hindi " , " English " , " Math " ] }

{ " _id " :ObjectId ( " 60ad0224e47de45e5e523e22 " ) , " StudentName " : " Gaurav " , " Section " : " A
" ," Marks " : 90 , " Subject " : [ " English " ] }

{ " _id " : ObjectId ( " 60ad0224e47de45e5e523e23 " ) , " StudentName " : " Ajay " , " Section " : " A
" , " Marks " : 70 , " Subject " : [ " Math " ] }

{ " _id " : ObjectId ( " 60ad0224e47de45e5e523e24 " ) , “StudentName " : " Ankur " , " Section " : "
B" , “Marks ":10, “Subject”:[“Hindi”]}
{ " _id " : ObjectId ( " 60ad0224e47de45e5e523e25 " ) , " StudentName " : " Sunil " , " Section " : " B "
, “Marks " : 70 , " Subject " : [ " Math " ] }

{ " _id " : ObjectId ( " 60ad0224e47de45e5e523e26 " ) , " StudentName " : " Preeti " , " Section " : " C
" ," Marks " : 80 , " Subject " : [ " Hindi " , " English " ] }

{ " _id " : ObjectId ( " 60ad0224e47de45e5e523e27 " ) , " StudentName " : " Anuj " , " Section " : " C
" , " Marks " : 50 , " Subject " : [ " English " ] }

{ " _id " : ObjectId ( " 60ad0224e47de45e5e523e28 " ) , " StudentName " : " Palka " , " Section " : " D
" , "Marks " 40 , " Subject " : [ " Math " ] }

{ " _id " : ObjectId ( " 60ad0225e47de45e5e523e29 " ) , " StudentName " : " Soniya " , " Section " : " D
" ," Marks " : 20 , " Subject " : [ " English " , " Math " ] }

You might also like