Mongodb
Mongodb
To connect to mongodb:-
const db =
'mongodb+srv://NamanKothari:namankothari@cluster0.ssrsv38.mongodb.net/
cardbase?retryWrites=true&w=majority'
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:-
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
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:-
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:-
* doesn’t show a database which doesn’t have even one record in it.
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)
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.
* 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!
Conditions:-
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.
INDEXING:- IMP
22- db.empofstylabs.getIndexes() -> predefined functions that tells us the index which is by default
applied on the _id of the document.
To apply indexes in your own properties from the by default _id indexes:-
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.
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:-
1.1db.student.aggregate([{"$project":{StudentName:1,Section:1,Marks:1}}]);
selects the field specified and displays ONLY those fields that we have selected(by
keeping its number 1).
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.
**!! 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.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:-
👆(1) 👆(multiple)
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.
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.
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.
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:-
{ " _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 " ] }