Skip to main content

Database : MongoDB


# SQL (structured query language) / RDBMS (Relational DBMS)
- Table- row (table format) (tabular design)

- table-table relation (primary, foreign key)
- define schema (schema is collection of DB objects associated with one particular DB username. Logical structure of data.)
- insert, fetch, update, remove (CURD) -> Create, Update, Retrieve, Delete
- Example: MySql, MS-SQL (includes defined property (eg. id, name))

# Distributed DBMS (Non- RDBMS)
- Collection (table )-> documents (but no relation)
- No Schema
- Documents (JSON Objects) within collection
- is highly scalable and can includes various property (eg. id, name, address..), can define field
- Example: No SQL type (MongoDB) and nested object
- MongoDB is a general-purpose, doc-based, distributed DB built for modern app developers and for the cloud era. Global cloud DB on AWS, Azure.
-Mongodb automatically set id (object id) unique key (primary key)

Important Command (MongoDB):
  1. mongo (shows version and connect to localhost)
  2. show dbs (shows list of dbs)
  3. use db_name (creating db)
  4. db.col_name.insert({
          name: 'Ram',
          addr:{
               perm: 'bkt',
               temp: ['pokhara', 'ktm']
           }})
     5. db.col_name.find({}).pretty() //shows json format with pretty format with nested object 

        db.col_name.find({}).limit(3)
// To find: find, findOne, findById
     6. db.col_name.count() //count the object
     7. update and insert
        db.col_name.update({query_to_find}, {$set: {key_value_pair}}, {multi: true, upsert:true});
     8. db.col.deleteOne( {"_id": ObjectId("id_number")});


     9. db.users.drop()

# DB (MongoDB use)
1. Native MongoDB (driver install)
2. ODM use (mongoose)
- ODM (Object Document Modelling) - Document based DBMS
  • schema based solution
  • valiadtion (required, unique, ..)
  • data type definition -> string, number, boolean, date, ObjectID
  • middleware in db
  • highly reusable code - db model
  • is mongodb object modelling tool designed to work in asyn env. (ODM)

- ORM (Object Relational Mapping) - RDBMS

ORM

- No sql but we make schema using ORM.
- Relational making
- Sequelize (promise-based ORM for Node.js)

# Mongoose (npm i mongoose --save)

- is object data modeling (ODM) library for MongoDB and Node.js
- it manages relationship between data, provides schema validation and is used to translate between an object in code and the representation of those objects in MongoDB.
- Object mapping between node and mongo DB managed via mongoose.
- Schema-based solution (project vision clear)
Mongoose db Connection
1.Event-based (Standard-based)
- Event trigger makes listeners and listeners do execution. eg: Click event
2. Connect Method
3. Create Connection Method

Web Application Development

1. Client-Side (Front End) eg(google material design, twitter bootstrap)
2. Server Side (Back End)

#Mongoose Command (CRUD Operation)

Connection Command
1. mongoose.connect()
2. mongoose.createConnection()
3. Event based
- ensuring connection -> callback and event based solution (.once(), .on())
Insertion
- dbModel.save(callback)
Find
- dbModel.find({query}, callback) //it returns array
- dbModel.findOne({query}, callback) //it returns object
- dbModel.findById(id, callback)
Update
- dbModel.update({query}, $set: {new property & value}, callback);
- db.dbModel.find({}, callback){
         document.name = 'new name';
         document.save(callback);
}
- db.findByIdAndUpdate(id, {new data to be updated}, callback);
Delete
- dbModel.remove({_id:id}, callback)
- dbModel.findByIdAndRemove(id, callback)

# Backup and Restore
Types:
1. bson data (mongodb to mongodb transfer only)
- mongodump
- bson file will be saved.
Command:
a) mongodump
- cd dump
- code .
- all the dbs will be shown
- myprojectdb(our db)
   - products.bson
   - products.metadata.json
- mongorestore
b) bson data restore
- cd ..

Important:

- cmd -- mongodump (backup all db into default dump folder.)
- mongodump --db_name (backup single db)
- mongodump --db db_name (shorthand -d db_name) -o db/backup/db_name(backup single db with other than default folder)
- cd dump - mongorestore --drop db/backup (drop backup db)
-parseIn() -> parse a string and returns an integer.

2. json data
#Backup cmd
mongoexport --db db_name --collection col_name --o path_to_my_backupFolder with jsonfile (.json extension)
Example:  
mongoexport --db myprojectdb --collection users --o new/backup/users.json
json= object

# Restore cmd
mongoimport --db db_name --collection col_name path_to_json_file
Example:
mongoimport --db myprojectdb --collection students users.json

3. csv
# Backup
cmd export -> mongoexport --db db_name collection col_name --type = csv --fields 'comma, separated header name like name, address, phone' --out path_to_save_csvfile (.csv extension for file )
Example:
mongoexport --db myprojectdb collection students --type = csv --fields 'id, username, password, role' --out backup/users.csv
# Restore
mongoimport --db myprojectdb --collection teachers --type = csv backup/abc.csv --headerline (name will be saved from top row)
Example:
mongoimport --db flipkart --type= csv flipkart.csv --headerline

Note: mongodump (backup) and mongorestore (restore) always comes in pair.
mongoexpert and mongoimport always comes in pair
- mongodump (backup) and mongorestore (restore) can not be done. Likewise, mongoexport (backup) and mongorestore(restore) can not be done.

Note: Robomongo (Robo 3D) - UI based DB
MongoDB (compass UI based DB)

Comments

Popular posts from this blog

Deploy react app on digitalocean using nginx

Source:  https://www.learnwithjason.dev/blog/deploy-nodejs-ssl-digitalocean/ Source:  https://www.digitalocean.com/community/tutorials/how-to-set-up-nginx-server-blocks-virtual-hosts-on-ubuntu-16-04 Source:  https://www.youtube.com/watch?v=vRrhQwNixlc https://www.youtube.com/watch?v=pyxXCwgWdMw https://dev.to/xarala221/the-easiest-way-to-deploy-a-react-web-application-2l8a 1. Create a new droplet on DigitalOcean. Choose the $5/month option with Ubuntu 16.04.1 x64. Select a region closest to your users. 2. Finally, add your SSH key and ls -la ~/.ssh # This copies the key so you can paste with command + V pbcopy < ~/.ssh/id_rsa.pub # This prints it in the command line for manual copying cat ~/.ssh/id_rsa.pub   3.  Add your SSH key to the droplet Click “Add SSH Key” to save it, then make sure it’s selected, name your droplet, and hit the big “Create” button to get your server online. Your new droplet will display

Gallery

https://fancyapps.com/fancybox/3/ <!-- 1. Add latest jQuery and fancybox files --> <script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" /> <script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js"></script> $ ( function () { if ( $ ( "[data-fancybox]" ). length ){ $ ( "[data-fancybox]" ). fancybox (); } });

Javascript: Array

ARRAY // homogenious and heterogenious array  var a = 'I am here'; var status = true; //array -> multiple values var arr = new Array(); //constructor method var arr1 = []; //bracket notation Example: var hobbies = ['dancing', true, 3423,{ //multiple type data collection values dance: true, singing: false }, []];