MongoDB: Introduction
Part 2: MERN STACK Series
Welcome back to the MERN STACK series.
In the first part, we learnt about some terms of MERN STACK.
First part link:🔗https://deepshah1309.medium.com/part1-mern-stack-series-deep-shah-6cb9fa248bc6
Now in this blog, I am going to explain MongoDb in detail.
What is MongoDB?😎
- Open Source
- Document oriented Database
- No SQL
- Does not require RDBMS(relational database management system)
5.Stores the data in JSON format(JSON-javascript object notation)
MongoDB VS MYSQL
MYSQL: It uses structured query language to access stored data .in this format schemas are used for DB structure and also utilizing tables a way for standardizing datatypes. It uses RDBMS.these relations help to structure the data and also organize the relations between tables. It is being used by many database-driven applications.
MongoDB: It’s the less-restrictive format and higher performance make it a better choice, particularly when availability and speed are primary concerns.
MongoDB COMPASS: It is a GUI(Graphical user interface) for MONGODB.it is also maintained by MongoDB itself.it allows you for smart decisions based on the document structures with great visualization.
download MongoDB compass:
🔗https://www.mongodb.com/try/download/compass
MongoDB ATLAS:
It is a fully managed cloud database developed by MongoDB.it handles complexity, management,and deployment on the Cloud service providers(Azure,GCP, AWS)
SignIn to MongoDb atlas:
🔗:https://www.mongodb.com/cloud/atlas
Fig 1 below shows the clear conceptual way to understand the structure
What is Mongoose?
Mongoose is an object modeling tool to work in an asynchronous environment.it provides schema-based solutions.it includes query building, validation, etc. It supports both promises and callbacks.
In our Project structure, we will be having two folders (Client, Server)
On the client-side, we will be designing awesome, flexible UI components by ReactJs.
On the server-side, we will be managing requests, database models, Database CRUD operations, middlewares etc.(Will be covered in detail in the project structure part blog)
let’s say we have a server directory in which we have package.json,index.js and node_modules(directory)
in this directory run the following command
npm i mongoose
it installs the package mongoose.
Let’s connect the database😎.
in the index.js file
mongoose model() function:
this function of the mongoose module is used to create a collection of a particular database.
const collections = mongoose.model("Your_COllection_name", collection_schema)
syntax:
mongoose.model(<Collectionname>, <CollectionSchema>)
Example:
const mongoose = require(‘mongoose’);// Database Connection
mongoose.connect(‘mongodb://127.0.0.1:27017/userdb’, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});const Schema=mongoose.schema;//schema creationconst userSchema=new Schema({
name: { type: String },
age: { type: Number },location:{type:String},
});// User model//mongoose.model(<Collectionname>, <CollectionSchema>)
const UserC= mongoose.model(‘User’,userSchema );//here first parameter “User” is the collectionname//storing one record to User collectionvar new_user_to_collection=new UserC({
name:"Anonymous",
age:35,
location:"india",})
//The save() function is used to save the document to the databasenew_user_to_collection.save((err,result)=>{if(err){//it is err object if it is null then else part will be executed and if it has some errors to display then if part will be executed.console.log(err);
}
else{//record added to collection
console.log(result);
}})
Mongoose find() function:
It is used to find particular documents in the collection.
it takes 3 args(arguments)=>
- Condition
- Query Projection
- general query options like=>(limit,skip …)
let’s understand it with an example
UserC.find({name:"abc"},{age:0},(err,docs)=>{if(err){
console.log(err);}else{console.log(docs);
}
});
//here first arguement {name:"abc"} is condition ,second argument is age:0 (note:{age:0} doesn't mean that it will find documents having age :0 ....it is for query projection ...means in the results age field will not be included.
Let’s see an example with all arguments:
UserC.find({age:{$gte:10}},null,{limit:2},(err,docs)=>{
if(err){console.log(err);
}
else{console.log(docs);
}
});
//first argument:{age:{$gte:10}} means find all documents which are having age greater than or equal to 10.
//second argument:null(means no projection is specified..all fields will be included in the result.)
//third argumenet:general queries{limit:2} means return 2 documents with the matching condition
mongoose Update() function:
It is used to update one document in the database without returning it.
UserC.update({name:"cba"},(err,result)=>{if(err){
console.log(err);}
else{console.log(result);
}
}
)
//Note:here result will include properties like {ok:'1',modified:'1'}
and this function will update the first document in the collection
"abc"=>"cba"
mongoose updateOne() function:
4 parameters
(filter,update,options,callback)
UserC.updateOne({age:{$gte:10}},{name:"cdsa"}, function (err, docs) {if (err){console.log(err)}else{console.log(docs);}});
//Understand the working of this function:
first argument:{age:{$gte:10}} .it is condition ...(age greater than or equal to 10)
second argument makes the update ..changes name of the first document which matches the condition to cdsa
mongoose updateMany() function:
it will update all the documents which matches the filter argument
UserC.updateMany({age:{$gte:5}},{name:"abcdefg"},(err,docs)=>{if (err){console.log(err)}else{console.log(docs);}
});
We have now reached the end of the blog !
In this blog we learnt mongodb intro,mongodb vs mysql,mongodb compass,mongodb atlas,mongoose package,mongoose connection,mongoose schema creation,mongoose model creation(collection+schema),mongoose save method to add the document to collection,update method,updateOne,updateMany methods etc.
Stay tuned for upcoming Blogs😎
Don’t forget to follow The Lean Programmer Publication for more such articles, and subscribe to our newsletter tinyletter.com/TheLeanProgrammer