Mongo DB is document based No SQL database.
Advantange of Mongo DB
- Clear structure of object
- Less Schema
- No complex query and query join
- Easy to scale
- Faster to store and access data.
Download & Install Mongo DB Community edition for windows
Download link:
Install
- Run Mongo DB installer
- Install Mongod as service
Check mongodb version
mongo --version
Starting Mongo DB(Open terminal or Window DOS, Shell)
mongod
Use Mongo DB shell
mongo
Choose or create new database
Syntax:
use database_name
Example:
use capscom
To check current database
db
Show all databases
show dbs
Drop database
db.dropDatabase()
Create collection(Like table)
db.createCollection(collection_name)
Show created collections
show collections
Drop collection
db.collection_name.drop()
CRUD implementation in Mongo DB
Create or Insert records
db.collection_name.insertOne() | Insert single record |
db.collection_name.insertMany() | Insert many records |
Retrieve or fetch records
db.collection_name.find() | Retrieve all documents |
db.collection_name.find().pretty() | Retrieve all documents in formated form |
db.collection_name.findOne() | Retrieve single document |
Update record
db.collection_name.updateOne(<filter>, <update>) | Update document |
db.collection_name.updateOne({field_name: value}, {$set: {field_name: value}}) |
|
db.collection_name.updateMany(<filter>, <update>) | Update many documents |
db.collection_name.updateMany({field_name: value}, {$set: {field_name: value}}) |
Remove records
db.collection_name.remove(condition, FLAG) // FLAG can be 1 or true
// One is declaring only one record will delete at a time
Remove all records
db.collection_name.remove({});
Remove a single record
db.collection_name.remove({country: 'India', 1})
Remove all matched records
db.collection_name.remove({country: 'India'})
Where clause with operators
Equality | db.collection_name.find({'field_name': value}); |
Greater than | $gt |
db.collection_name.find({field_name: {$gt: value } } ) |
|
Greater than and equal to | $gte |
db.collection_name.find({field_name: {$gte: value } } ) |
|
Less than | $lt |
db.collection_name.find({field_name: {$lt: value } } ) |
|
Less than and equal to | $lte |
db.collection_name.find({field_name: {$lte: value } } ) |
|
Not equal to | $ne |
db.collection_name.find({field_name: {$ne: value } } ) |
|
In | $in |
db.collection_name.find({field_name: {$in: [item1, item2] } } ) |
|
Not in | $nin |
db.collection_name.find({field_name: {$nin: [item1, item2] } } ) |
|
AND | $and |
db.collection_name.find( $and: [ {field_name: value}, {field_name: value} ] ) |
|
OR | $or |
db.collection_name.find( $or: [ {field_name: value}, {field_name: value} ] ) |
|
NOT | $not |
db.collection_name.find( { field_name : {$not: { $operator: value } } } ) |
Example
db.products.find({'qty': {$gt: 10}});
// will retrieve all products that have qty greater than 10
Limit & Skip documents in mongodb
db.collection_name.find().limit(n).skip(m)
// where n is how many document will fetch and m is how many document will skip.
Fetch documents in ascending or descending order
Fetch records in ascending order
db.collection_name.find().sort({field_name: 1})
Fetch records in descending order
db.collection_name.find().sort({field_name: -1})
Mongoose An ODM(Object Data Modeling) for mongodb
Install mongoose using npm
npm install mongoose
Load mongoose on application
let mongoose= require('mongoose')
Create a connection
mongoose.connect('mongodb://localhost:27017/database_name')
Note: localhost can be replaced with 127.0.0.1
check mongoose connection status
mongoose.connection.on('connected', function(){
console.log('Connected with mongodb');
})
Create Schema for document models
Consider you have document users to store user information, so first of all we will create schema for users document which will be skelton of document.
Load Schema from mongoose
cons {Schema} = mongoose
Create user schema
let UserSchema=new Schema({
username: String,
email: String,
password: String
});
Create Model
const UserModel= mongoose.model('users', UserSchema);
CRUD Operations on mongoose.
Create |
await UserModel.create({ |
Read |
let users= UserModel.find({}); |
Update |
await UserModel.updateOne({ id: id_value }, { |
Delete |
let deletedUser=UserModel.findByIdAndDelete(id, (error)=>{ |