Exercises: MongoDB, cooking recipes
In this exercises you will try some simple operations with MongoDB.
Prerequisites
- Install MongoDB
- Install Robomongo or a similar GUI for MongoDB
- Start MongoDB:
run the file mongod.exe. On my Windows computer it resides in the folder C:\Program Files\MongoDB 2.6 Standard\bin
- Run Robomongo, and connect to MongoDB
Schema
Pen + paper: Make a simple schema for at database holding cooking recipes.
A recipe consists of
- a title
- a number of ingredients and
- some cooking instructions (a kind of algorithm)
- a category like "snack", "starter", "main course", "dessert", "breakfast" etc.
An ingredient consists of a number, a measure and a type. Example: 1 liter milk
Make collection
Make a new collection named cookbook.
Insert into the collection
Insert at least 5 documents into the collection. Simple recipes like "hardboiled egg", "fried egg", "pancakes", "omelet", etc. Instructions should be very short.
Some of the documents must have ingredients like milk, eggs and water.
Find documents in the collection using title and instruction
- Find all recipes with the title "pancakes".
- Find all recipes with a title that starts with the letter "p".
Hint: The regular expression /^p/ might be helpful.
- Find all recipes with a title that contains the letter "e".
Hint: The regular expression /e/ might be helpful.
- Find all recipes with a title that contains the letter "e" and an instruction that contains the letter "a".
- Find all recipes with a title that containt the letter "e" or an instruction that contains the letter "a".
Update the documents
Add another field to the recipe documents: howMany
Howmany persons is this recipe for?
Find documents in the collection using the ingredient array
- Find all recipes with the ingredient "egg".
- Find all recipes with the ingredient "egg" and "sugar".
- Find all recipes with the ingredient "egg" or "sugar".
- Find all recipes with exactly 3 ingredients.
Hint: Use the operator $size, example
- Find all recipes with at least 3 ingredients.
Hint: Read (some of) this post In MongoDB, how do I find documents where array size is greather than 1 ?
Counting the number of documents in a collection
General hint: The collection count method
- Count how many recipes has the title "pancakes".
- Count how many recipes has exactly 3 ingredients
Distinct values
General hint db.collection.distinct()
- Get the list of all ingredients in all the recipes.
- Same as above, but sorted.
db.cookbook.distinct("ingredient.name").sort();
Cursors and iteration
Hint: cursor.forEach()
- Iterate all the recipes printing the titles.
Map Reduce
- For each category ("dessert", "breakfast", etc.) find the number of dishes in the category.