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.
- 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 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
- SQL vs NoSQL when selecting a database for your application
- MySQL vs MongoDB: basic differences
- More on SQL vs NoSQL
Installation guide: https://docs.mongodb.com/manual/installation/
MacOS:
brew install mongodb
sudo mkdir -p /data/db
sudo chown -R `id -un` /data/db
- from you terminal run
mongod
- To access the Mongo CLI, open another tab in your terminal and write
mongo
- You can perform any database commands from the mongo CLI
- Here's a very useful cheat sheet: https://blog.codecentric.de/files/2012/12/MongoDB-CheatSheet-v1_0.pdf
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.
show dbs
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
- collections in MongoDB are like tables in PostgreSQL
db.createCollection('pokemon') // cannot have '-' in name
- inserting one document:
db.pokemon.insert({ _id: 1, name: "Bulbasaur", })
- inserting multiple documents:
db.pokemon.insertMany([ { _id: 2, name: "Ivysaur" }, { _id: 3, name: "Venusaur" } ])
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/})
- 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.
db.pokemon.remove({}) // you need the {}
db.pokemon.deleteMany({})
- CLick here if you want to know the difference between
Remove
anddeleteMany
- Mongo DB is not meant for relational purpose but it still supports nested querying.
- Let's create another collection in our
pokedex
database calledmoves
, and insert some moves in theredb.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()
- 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.
- 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. - Create some of the moves. Here's the link for moves https://pokeapi.co/api/v2/move/
- Update the pokemon and assign moves
References: