Skip to content

Instantly share code, notes, and snippets.

@anharathoi
Last active June 18, 2019 01:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anharathoi/f76930dc7351a4d9fcdfa1a82f703cc3 to your computer and use it in GitHub Desktop.
Save anharathoi/f76930dc7351a4d9fcdfa1a82f703cc3 to your computer and use it in GitHub Desktop.

MongoDB

MongoDB is a document database designed for ease of development and scaling. We have been using in memory data in our Express app so far. But to build our full-stack MERN application we need persistence for which we will be using MongoDB. Persistence is storing the data in some manner, so that the data is accessible even if the application is shutdown and restarted or across multiple instances of applications.


What is a document database?

  • A document is simply a data structure composed of field and value pairs, e.g.,
     {
     	name: "Luke Skywalker",
     	height: "172",
     	mass: "77",
     	hair_color: "blond",
     	skin_color: "fair",
     	eye_color: "blue",
     	birth_year: "19BBY"
     }
    
  • A record in MongoDB is a document. MongoDB documents are similar to JSON objects. The values of fields may include other documents, arrays, and arrays of documents.

Relational DBMS and Mongo DB

Relational Database Mongo DB
Database Database
Tables Collection
Rows/Records Documents
Columns Fields

I found these links to be very good in terms of explaining differences between SQL and NoSQL databases


Installation

Installation guide: https://docs.mongodb.com/manual/installation/

MacOS:

brew install mongodb
sudo mkdir -p /data/db
sudo chown -R `id -un` /data/db

Run mongoDB and access the CLI

You can also use brew to run mongodb server

  • to show all services installed via brew run:
    brew services list
    
  • to run mongod
     brew services start mongodb
    
  • to access mongo CLI run this from you terminal
     mongo
    

Notes:

Mongod stands for “Mongo Daemon”. mongod is a background process used by MongoDB. The main purpose of mongod is to manage all the MongoDB server tasks. For instance, accepting requests, responding to client, and memory management.


Mongo CLI operations

Show all databases:

show dbs

Create / Use Database

use pokemondb
  • this command will create a database if it does not exist
  • However the database will not be saved unless it has a collection in it

Create Collections

  • collections in MongoDB are like tables in PostgreSQL
db.createCollection('pokemon') // cannot have '-' in name

Create documents

  • inserting one document:
     db.pokemon.insert({
     	_id: 1,
     	name: "Bulbasaur",
     })
    
  • inserting multiple documents:
     db.pokemon.insertMany([
     	{
     		_id: 2,
     		name: "Ivysaur"
     	},
     	{
     		_id: 3,
     		name: "Venusaur"
     	}
     ])
    

Read documents

This are all the commands you can use to read your data:

db.pokemon.find() // finds all
db.pokemon.findOne({name: /Ivysaur/})
db.pokemon.find({name: /saur/})

Update documents

  • To update an existing document, we first find it and then set the new value with the following command:
db.pokemon.update({name: "Ivysaur"}, {$set:{name: "IVYSAUR"}})

  • If we run the same command with upsert=true option, it will see that there is no matching document which it can update and will insert a new one.
db.pokemon.update({id:19},{$set:{name:'newsaur',height:'5 m'}},{upsert:true})

Now what if we decide to have an additional field for moves for all the pokemon? We can add a column to the existing documents with the following command.

db.pokemon.update({},{$set:{"moves":''}},false,true)

Here the '{}' implies there is not conditions or restrictions and all the documents need to be updated.


Delete documents

db.pokemon.remove({}) // you need the {}
db.pokemon.deleteMany({})
  • CLick here if you want to know the difference between Remove and deleteMany

Nested queries

  • Mongo DB is not meant for relational purpose but it still supports nested querying.
  • Let's create another collection in our pokedex database called moves, and insert some moves in there
     db.createCollection('moves')
    
     db.moves.insert([{ _id:1, name:'pound'}, { _id :2, name:'karate chop'},{_id :3, name:'double slap'}])
    
  • Now let's assign some moves to our pokemon in the pokemon collection:
      db.pokemon.update({id:1},{$set:{moves:[2,3]}})
    
      db.pokemon.update({id:2},{$set:{moves:[1,3]}})
    
      db.pokemon.update({id:3},{$set:{moves:[1,2]}})
    
  • To get all the pokemon which have the move 'karate chop', we will issue a nested query like this.
     db.pokemon.find({moves: db.moves.findOne({'name': 'karate chop'})._id}).pretty()
    

Dropping collections:

  • If for some reason you want to delete your collections, this is the command:
     db.nameOfCollection.drop()
    

Challenges:

A. Use the pokemon API for reference.

  1. Create the first ten pokemon with name and image url attributes inside the pokemon collection. The image link can be found under the sprites key, Command + F to search if you can't find it.
  2. Create some of the moves. Here's the link for moves https://pokeapi.co/api/v2/move/
  3. Update the pokemon and assign moves

References:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment