Exercises: MongoDB, cooking recipes

In this exercises you will try some simple operations with MongoDB.

Prerequisites

  1. Install MongoDB
  2. Install Robomongo or a similar GUI for MongoDB
  3. Start MongoDB:
    run the file mongod.exe. On my Windows computer it resides in the folder C:\Program Files\MongoDB 2.6 Standard\bin
  4. Run Robomongo, and connect to MongoDB

Schema

Pen + paper: Make a simple schema for at database holding cooking recipes.

A recipe consists of

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

  1. Find all recipes with the title "pancakes".
  2. Find all recipes with a title that starts with the letter "p".
    Hint: The regular expression /^p/ might be helpful.
  3. Find all recipes with a title that contains the letter "e".
    Hint: The regular expression /e/ might be helpful.
  4. Find all recipes with a title that contains the letter "e" and an instruction that contains the letter "a".
  5. 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

  1. Find all recipes with the ingredient "egg".
  2. Find all recipes with the ingredient "egg" and "sugar".
  3. Find all recipes with the ingredient "egg" or "sugar".
  4. Find all recipes with exactly 3 ingredients.
    Hint: Use the operator $size, example
  5. 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

  1. Count how many recipes has the title "pancakes".
  2. Count how many recipes has exactly 3 ingredients

Distinct values

General hint db.collection.distinct()

  1. Get the list of all ingredients in all the recipes.
  2. Same as above, but sorted.
    db.cookbook.distinct("ingredient.name").sort();

Cursors and iteration

Hint: cursor.forEach()

  1. Iterate all the recipes printing the titles.

Map Reduce

  1. For each category ("dessert", "breakfast", etc.) find the number of dishes in the category.