Ultimate Mongodb Cheatsheet
Ultimate Mongodb Cheatsheet
MONGODB
CHEATSHEET
INTUITION
KEY DIFFERENCES BETWEEN SQL AND NOSQL
SQL NOSQL
CRUD OPERATIONS
Create: Insert one or more records into the database
PRIMARY KEYS
Always unique for each document in a collection
Cannot have null or missing values
In MongoDB, this is the “_id” key and is added to every document by default:
"_id" : ObjectId("5c92eca2cc7efa53af5dae22")
RELATIONSHIPS IN DATA
User:
{
"_id" : ObjectId("5c943413cc7efa53af5dae24"),
"user_id" : 3173,
"name" : "helen",
"age" : 32
}
Blog Post:
{
"_id" : ObjectId("5c943545cc7efa53af5dae25"),
"post_id" : 5186,
"user_id" : 3173,
"body" : "Lorem ipsum dolor sit amet",
"topic" : "health and wellness",
"likes" : 57,
"dislikes" : 31
}
These goals often conflict with each other! It’s difficult to perfectly achieve both of them,
but it’s helpful to try to get as close as we can.
2 PRACTICAL
STARTING UP THE MONGO SHELL
In one terminal window, type mongod and hit enter. This will start your MongoDB server.
*Note: You will also need to have a MongoDB server running to use MongoDB Com-
pass.
Open up another terminal, type mongo and hit enter
You should now have a running MongoDB shell!
Once you’re using a database, type show collections and hit enter to see what collec-
tions you have.
To start working with data in a collection you can use the CRUD operations shown below!
CRUD OPERATIONS IN THE MONGO SHELL
Create: Inserts a document with a name of patrick
db.collection.insert({“name”: “patrick”})
Update: Replaces the first document found with a country of “US” with a new docu-
ment, containing only a country of “USA”
db.collection.update({“country”: “US”}, {“country”: “USA”})
You can also combine several queries with $and and $or!
Returns all posts with less than 43 likes and more than 25 dislikes
{$and: [{"likes": {$lt: 43}}, {"dislikes": {$gt: 25}}]}
Returns all posts with less than than 34 dislikes or where the topic is not equal to cooking
{$or: [{"dislikes": {$lt: 34}}, {"topic": {$ne: "cooking"}}]}