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

NodeJS: Request and Respose Objects

# req Objects - req - req.body, req.queries, req.validationerrors - res.headers, req.users, req.file, req.assert - req.params, req.checkbody #res Objects - res.send, res.end, res.json, res.render, res.status, res.sendStatus # - .limit(4) //limit only upto 4 docs - skips(3) //skip first 3 docs - exe //query build and then execute, it is also callback function of mongoose. - sort({_id: -1}) //for decending order - populate('userId') //populating data inside the reference.

Javascript: Object to Array and Array to Object

Output: Final Array [ { mango: 1 }, { apple: 2 }, { banana: 3 }, { orange: 1 }, { watermelon: 1 }, { papaya: 1 } ] Output: Final Object { mango: 1, apple: 2, banana: 3, orange: 1, watermelon: 1, papaya: 1 }

Github Tutorial

GitHub brings together the world's largest community of developers to discover, share, and build better software. Delivered through software as a service(SAAS) business model 2008 by linus (Owner: Microsoft)  #Create New Repository in Github New Repository Add Repository Name and description Public / Private, initialize this repo with Read Me Create repository create a new repository on the command line echo "#test" >> README.md git init git add README.md git commit -m "first commit" git remote add origin https://github.com/sinuna/test.git git push -u origin master …or push an existing repository from the command line git remote add origin https://github.com/sinuna/firstRepository.git git push -u origin master …or import code from another repository You can initialize this repository with code from a Subversion, Mercurial, or TFS project. Initialize Repo $ git init Clone Repo $ git clone https://github.com...