8.MongoDB

What is MongoDB?

MongoDB is a NoSQL database.

In Mongo,

  • each database contains one or more collections (Tables).
  • Each collection contains one or more data structures called document (Rows)
  • Each document contains a data about a single entity.
    For example like one blogPost, one user, one review.
  • Document will have a data format like JSON.

MongoDB is a document database with scalability and flexibility that you want and with the querying and indexing that you need.

Key Features of MongoDB

  • Document based - MongoDB stores data in documents (field value pair data structures like JSON, NoSQL)
  • Scalable - Very easy to distribute data across multiple machines as your users and amount of data grows.
  • Flexible - No document data schema required, so each document can have different number and type of fields.
  • Performant - Embedded data models,indexing, sharding, flexible documents, native duplication, etc
  • Free and open source, published under the SSPL License.

BSON

  • MongoDB uses a data format called BSON for data storage.
  • BSON is like JSON but typed(means all values will have data type such as string, boolean, double etc,.). So MongoDB documents are typed.
    Like JSON, BSON documents will also have fields and data stored in key-value pairs.
  • Embedding/Denormalizing - Including related data into a single document. This allows for quicker access and easier data models.
  • Maximum size of BSON document is 16MB.
  • Each document contains unique Id, which acts as a primary key of the document. This is automatically generated with ObjectId datatype each time there is a new document.

Install MongoDB

Install on MacOS
Software -- Community server -- download current release

  1. sudo copy all executables in bin to Users/local/bin
  2. sudo mkdir Users/local/data/db
  3. sudo chown -R id -un /Users/local/data/db

One more way to install - it worked for me

brew uninstall mongodb
brew tap mongodb/brew

brew install mongodb-community

To run mongo demeon server -- mongod --dbpath /Users/local/data/db
after running the demeon, open other terminal window or shell and run mongo to open mongoDB shell.

To create a local database in MongoDB

db natours-test -- To create a database
db.tours.insertOne({name: "The Forest Hiker", price: 297, rating: 4.7}) -- To create a collection in the current database, db stands for current database i.e., natours-test. tours is the name of the collection. name is the name of the document. insertMany to insert many documents, insertOne to insert one document.
db.tours.find() -- To check the documents of a particular collection.

show dbs -- shows all the databases in MongoDB
use <databasename> -- to switch to another database, if there is a database it will switch otherwise it will create a new database and switch to new database. show collections -- shows all collections of a current database
quit() - To quit from the shell.
cls or ctrl+l -- to clear mongo shell.

Creating Documents

Insert Many function to pass in array with more than one document. db.tours.insertMany([{name: "The sea Explorer", price: 497, rating: 4.8}, {name: 'The Snow Adventure', price: 997, rating: 4.9, difficulty: "easy"}])

Find function to check the documents of a collection db.tours.find()

Querying or Reading Documents

To query all the documents in a collection
db.tours.find()
where tours is the collection name

To query a particular document, whose name we know
db.tours.find({name: "The Forest Hiker"})
In the same way, we can search for any id like name, difficulty, price etc,.

To query for the documents whose price is less than or equal 500
db.tours.find({price: {$lte: 500} })
here lte is a query operator that stands for less than or equal to
$ sign is given for all the mongo operators in db.

To query with two search criteria at the same time price less than 500 and rating is greater than or equal to 4.8 db.tours.find({price: {$lt: 500}, rating: {$gte: 4.8} })

price less than 500 or rating is greater than or equal to 4.8 db.tours.find({$or: [ {price: {$lt: 500}}, {rating: {$gte: 4.8}} ]})

To have only some fields in the output db.tours.find({$or: [ {price: {$lt: 500}}, {rating: {$gte: 4.8}} ]}, {name:1}) This will have only name field in the output

Updating Documents

update one record explicitly. updateOne will work only on the first record that matches the condition.

db.tours.updateOne({name: "The Snow Adventure"}, { $set: {price: 597}})
first we need query the records, which we need to update and then set the fields.

update many records

db.tours.updateMany({ price: {$gt:500}, rating: {$gte: 4.8} }, { $set: {premium: true} })

while updating, if the set field is available, it will just set the value. If set field is not available, it will create a field and sets the value with given value.

Deleting Documents

deleteOne will work only on the first record that matches the condition.

db.tours.deleteMany({rating: {$lt:4.8}})

This deletes all the records, whose rating is less than 4.8

db.tours.deleteMany({})

This deletes all the documents of a collection. empty {} matches with all the documents.

Compass App for MongoDB

Compass is GUI for MongoDB

Install Compass

Atlas

Atlas is a cloud database service provider, which manages and scales the databases.

Access to Atlas

cluster is an instance of database.

cluster gives an empty database that can be connected with our local database.

MongoDB Driver

MongoDB driver allows node code to access and interact with a mongoDB database.

npm i mongoose

  • Mongoose is an object Data Modeling (ODM) library for MongoDB and Node.js, a higher level of abstraction.
    Express is a layer of abstraction over Node.
    Mongoose is a layer of abstraction over MongoDB
  • Mongoose allows for rapid and simple development of MongoDB database interactions.
  • Features: schemas to model data and relationships, easy data validation, simple query API, middleware, etc.
  • Mongoose schema: where we model our data, by describing the structure of the data, default values and validation.
  • Mongoose Model: a wrapper for the schema, providing an interface to the database for CRUD operations.

schema --> model

Mongoose is all about models, model is a blue print that we use to create a documents like classes in javascript.
For CRUD operations, we need a mongoose model