MongoDB Tutorial : This tutorial will give you great understanding on MongoDB concepts needed to create and deploy a highly scalable and performance-oriented database. You you master MongoDB from scratch. After the tutorial, you'll know how to use MongoDB in your projects effectively.
MongoDB is a document-oriented NoSQL database used for high-volume data storage. It contains the data model, which allows you to represent hierarchical relationships. It uses JSON-like documents with optional schema instead of using tables and rows in traditional relational databases. Documents containing key-value pairs are the basic units of data in MongoDB.
We will be using Windows as our operating system in this example.
Using terminal type: mongo
show dbs create db: use college then type db
*Minimum one collection and document create mandetory for showing db now show dbs
show collections db.collectionsname db.collectionsname.find() db.collectionsname.find().pretty()
How to delete database show dbs use dbName db.dropDatabase()
C: Create
db.collectionsName.insertOne({}) db.collectionsName.insertMany([{},{},{}])
R: Read
db.students.find({name:"dev das"}, {name:0}) { "_id" : ObjectId("633bbf0b9054cb32f0a15e2f"), "email" : "[email protected]", "mob" : 7111111111 } { "_id" : ObjectId("633bbf409054cb32f0a15e32"), "email" : "[email protected]", "mob" : 7111111111 } db.students.find({name:"dev das"}, {name:1}) { "_id" : ObjectId("633bbf0b9054cb32f0a15e2f"), "name" : "dev das" } { "_id" : ObjectId("633bbf409054cb32f0a15e32"), "name" : "dev das" }
U: Update
updateOne() => db.collectionName.updateOne(filter, update) updateMany() => db.collectionName.updateMany(filter, update)
D: Delete
deleteOne => db.collectionsName.deleteOne(filter) deleteMany => db.collectionsName.deleteMany(filter)
const {MongoClient} = require('mongodb');
// or
// const MongoClient = require('mongodb').MongoClient;
//connect with db
const url='mongodb://localhost:27017';
const client = new MongoClient(url) //new => create object
const databaseName = 'clg';
async function getData() {
const result = await client.connect();
const db = result.db(databaseName); //connect with database
const collection = db.collection("students") //connect with db collections
const response = await collection.find({}).toArray();
console.log(response);
}
getData();
const mongoose = require('mongoose');
//connect with DB
mongoose.connect('mongodb://localhost:27017/clg')
.then(()=>{
console.log('Connection successfull with DB');
})
.catch((err)=>{
console.log(err);
});
// Schema And Model
// Schema => Structure defined for document
// like: name: String, mob: Number, mobNoActive: true
// create Schema without required/mandatory
// const studentSchema = mongoose.Schema({ //new mongoose.Schema new keyword not mandatory
// name:String,
// mob: Number,
// roll:Number,
// fees:true,
// date:{
// type:Date,
// default:Date.now
// }
// })
// create Schema with required/mandatory
const studentSchema = mongoose.Schema({
name:{
type:String,
required:true
},
mob: {
type:Number,
required:true
},
roll:{
type:Number,
required:true
},
fees:{
type:Boolean,
required:true
},
date:{
type:Date,
default:Date.now
}
})
// Model => wrap full Schema is a model
// By using Model we can CRUD operation
//collection name alaways use singular
// ex: student not students, model create with pural ex: student to students
//create model
const StudentSchema = mongoose.model('student', studentSchema);
// How to insert document
// const createStudent = StudentSchema({
// name: "pratap",
// mob: 1010101010,
// roll: 1,
// fees: true
// })
// createStudent.save();
// or best way insert document
// create method
// add try catch for error handaling
// async await use for Promise return
const createStudents = async()=>{
try {
const createStudent = StudentSchema({
name: "hello",
mob: 10000000001,
roll: 10,
fees: true
})
const studentData = await createStudent.save();
console.log(studentData) //print insert data
} catch (error) {
console.log(error)
}
}
createStudents();
//Multiple documents insert
const createStudents = async()=>{
try {
const createStudent_1 = StudentSchema({
name: "stdudent 1",
mob: 91,
roll: 16,
fees: true
})
const createStudent_2 = StudentSchema({
name: "student 2",
mob: 81,
roll: 8,
fees: true
})
const createStudent_3 = StudentSchema({
name: "student 3",
mob: 71,
roll: 9,
fees: true
})
const createStudent_4 = StudentSchema({
name: "student 4",
mob: 41,
roll: 9,
fees: true
})
const createStudent_5 = StudentSchema({
name: "student 5",
mob: 51,
roll: 10,
fees: true
})
const studentData = await StudentSchema.insertMany([createStudent_1, createStudent_2, createStudent_3, createStudent_4, createStudent_5]);
console.log(studentData) //print insert data
} catch (error) {
console.log(error)
}
}
createStudents();
//Read documents with mongoose
const readDocuments = async()=>{
try {
// const readData = await StudentSchema.find() //all data
// const readData = await StudentSchema.find({fees:false}) //filter data
const readData = await StudentSchema.find({fees:false}).select({name:1, _id:0}).limit(1) // more filter data
console.log(readData);
} catch (error) {
console.log(error);
}
}
readDocuments();
//Update documents with mongoose
const updateDocuments = async(id)=>{
try {
// const updateData = await StudentSchema.updateOne({_id:id},{$set:{name:'abcd', mob:1231231230}})
const updateData = await StudentSchema.findByIdAndUpdate({_id:id},{$set:{name:'ABCD', mob:1011111}},{new:true})
console.log(updateData);
} catch (error) {
console.log(error);
}
}
updateDocuments('633c13da467bea9941ac7c4e')
// Delete document with mongoose
// const deleteDocuments =async (id)=>{
// try {
// const updateData = await StudentSchema.deleteOne({_id:id})
// console.log(updateData);
// } catch (error) {
// console.log(error.message);
// }
// }
// deleteDocuments('633c15b1ccc94f220dbe4fc5')
//Delete many document with mongoose
// const deleteDocuments =async (roll)=>{
// try {
// const updateData = await StudentSchema.deleteMany({roll})
// console.log(updateData);
// } catch (error) {
// console.log(error.message);
// }
// }
// deleteDocuments(8)
//Delete document by id with mongoose
const deleteDocuments =async (id)=>{
try {
const updateData = await StudentSchema.findByIdAndDelete({_id:id})
console.log(updateData);
} catch (error) {
console.log(error.message);
}
}
deleteDocuments('633d93de34e3e65b1852a1f4')
//Comaprison operator
//Read data with mongoose
const readDocuments = async()=>{
try {
// const readData = await StudentSchema.find() //all data
// const readData = await StudentSchema.find({fees:false}) //filter data
// const readData = await StudentSchema.find({fees:false}).select({name:1, _id:0}).limit(1) // more filter data
//Comparison operator
const readData = await StudentSchema
// .find({fees:{$eq: false}})
// .find({roll:{$gt: 7}})
// .find({mob:{$gte:1111111}})
// .find({roll:{$lt: 7}})
// .find({roll:{$in: [5, 16]}})
.find({roll:{$nin: [5, 16]}})
.select({name:1, _id:0})
console.log(readData);
} catch (error) {
console.log(error);
}
}
readDocuments();
// Logical Query Operator
//Read data with mongoose
const readDocuments = async () => {
try {
// const readData = await StudentSchema.find() //all data
// const readData = await StudentSchema.find({fees:false}) //filter data
// const readData = await StudentSchema.find({fees:false}).select({name:1, _id:0}).limit(1) // more filter data
// Logical Query Operator
const readData = await StudentSchema
// Logiacl query operator
// .find({$and:[{fees: false},{name:"pratap"}]})
// .find({$or:[{fees: false},{name:"pd"}]})
// .find({$nor:[{fees: false},{name:"pratap"}]})
.find({ roll: { $not: { $gt: 7 } } }) // NOT operator
.select({ name: 1, _id: 0 })
console.log(readData);
} catch (error) {
console.log(error);
}
}
readDocuments();
// Counting and Sorting
//Read data with mongoose
const readDocuments = async () => {
try {
// const readData = await StudentSchema.find() //all data
// const readData = await StudentSchema.find({fees:false}) //filter data
// const readData = await StudentSchema.find({fees:false}).select({name:1, _id:0}).limit(1) // more filter data
const readData = await StudentSchema
// Counting and Sorting
// .countDocuments() // or .count()
.find()
// .sort({name: 1})
.sort({name: -1})
.select({ name: 1, _id: 0, mob: 1 })
console.log(readData);
} catch (error) {
console.log(error);
}
}
readDocuments();
const mongoose = require('mongoose');
//connect with DB
mongoose.connect('mongodb://localhost:27017/clg')
.then(() => {
console.log('Connection successfull with DB');
})
.catch((err) => {
console.log(err);
});
// create Schema with required/mandatory
const studentSchema = mongoose.Schema({
name: {
type: String,
required: true, //validation
lowercase: true, //validation
trim: true, //validation
minlength: [3, 'Minimum Name length is 3'], //validation
maxlength: [10, 'Maximum Name length is 10'] //validation
},
mob: {
type: Number,
required: true,
min:[10, 'Minimum mobile no 9'], //validation
max:[16, 'Maximum mobile no 10'] //validation
},
roll: {
type: Number,
required: true
},
fees: {
type: Boolean,
required: true
},
date: {
type: Date,
default: Date.now
}
})
//create model
const StudentSchema = mongoose.model('student', studentSchema);
//multiple documents insert
const createStudents = async () => {
try {
const createStudent_1 = StudentSchema({
name: " Stdudent 1 extra space ",
mob: 91,
roll: 16,
fees: true
})
const createStudent_2 = StudentSchema({
name: "STUDENT 2",
mob: 81,
roll: 8,
fees: true
})
const createStudent_3 = StudentSchema({
name: "std 3",
mob: 71,
roll: 9,
fees: true
})
const studentData = await StudentSchema.insertMany([createStudent_1, createStudent_2, createStudent_3]);
console.log(studentData) //print insert data
} catch (error) {
console.log(error)
}
}
createStudents();
const mongoose = require('mongoose');
//connect with DB
mongoose.connect('mongodb://localhost:27017/clg')
.then(() => {
console.log('Connection successfull with DB');
})
.catch((err) => {
console.log(err);
});
// create Schema with required/mandatory
const studentSchema = mongoose.Schema({
name: {
type: String,
required: true, //validation
lowercase: true, //validation
trim: true, //validation
// minlength: [3, 'Minimum Name length is 3'], //validation
// maxlength: [10, 'Maximum Name length is 10'] //validation
},
mob: {
type: Number,
required: true,
// validate(value){
// if (value.toString().length < 10 || value.toString().length > 10) {
// throw Error('Please enter valid mobile number');
// }
// }
// or
validator:function(value){
return value.toString().length == 10;
},
message: 'Please enter valid mobile number'
},
roll: {
type: Number,
required: true
},
fees: {
type: Boolean,
required: true
},
date: {
type: Date,
default: Date.now
}
})
//create model
const StudentSchema = mongoose.model('student', studentSchema);
//multiple documents insert
const createStudents = async () => {
try {
const createStudent_1 = StudentSchema({
name: " Stdudent 1 extra space ",
mob: 9100000000,
roll: 16,
fees: true
})
const createStudent_2 = StudentSchema({
name: "STUDENT 2",
mob: 8100000000,
roll: 8,
fees: true
})
const createStudent_3 = StudentSchema({
name: "std 3",
mob: 7100000000,
roll: 9,
fees: true
})
const studentData = await StudentSchema.insertMany([createStudent_1, createStudent_2, createStudent_3]);
console.log(studentData) //print insert data
} catch (error) {
console.log(error)
}
}
createStudents();
const mongoose = require('mongoose');
const validation = require('validator');
//connect with DB
mongoose.connect('mongodb://localhost:27017/clg')
.then(() => {
console.log('Connection successfull with DB');
})
.catch((err) => {
console.log(err);
});
// create Schema with required/mandatory
const studentSchema = mongoose.Schema({
name: {
type: String,
required: true, //validation
lowercase: true, //validation
trim: true, //validation
minlength: [3, 'Minimum Name length is 3'], //validation
maxlength: [10, 'Maximum Name length is 10'] //validation
},
email: {
type: String,
required: true,
validate(value){
if (!validation.isEmail(value)) {
throw Error('Enter correct email id');
}
}
},
mob: {
type: Number,
required: true,
validator:function(value){
return value.toString().length == 10;
},
message: 'Please enter valid mobile number'
},
roll: {
type: Number,
required: true
},
fees: {
type: Boolean,
required: true
},
date: {
type: Date,
default: Date.now
}
})
//create model
const StudentSchema = mongoose.model('student', studentSchema);
//multiple documents insert
const createStudents = async () => {
try {
const createStudent_1 = StudentSchema({
name: "Stdudent 1",
email: '[email protected]',
mob: 9100000000,
roll: 16,
fees: true
})
const createStudent_2 = StudentSchema({
name: "STUDENT 2",
email: '[email protected]',
mob: 8100000000,
roll: 8,
fees: true
})
const createStudent_3 = StudentSchema({
name: "std 3",
email: '[email protected]',
mob: 7100000000,
roll: 9,
fees: true
})
const studentData = await StudentSchema.insertMany([createStudent_1, createStudent_2, createStudent_3]);
console.log(studentData) //print insert data
} catch (error) {
console.log(error)
}
}
createStudents();