MongoDB CRUD workshop

From Knowledge Kitchen
Jump to navigation Jump to search


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


Prerequisites

Schema

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

Mark up an example document in JSON syntax.

Each recipe consists of:

  • a title
  • some ingredients
    • an ingredient consists of a quantity, a unit of measurement, and a type.
    • example: 1 liter milk
  • some cooking instructions (a kind of algorithm)
  • a category like "snack", "starter", "main course", "dessert", "breakfast" etc.

Make a collection

Make a new collection named cookbook.

  • Hint: if you insert or import documents into a collection that doesn't yet exist, the collection will be automatically created.

Insert documents into the collection

Insert at least 5 documents into the collection.

  • Use 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 instructions

  1. Find all recipes with the title "pancakes".
  2. Find all recipes with a title that starts with the letter "p".
  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 contain the letter "e" or an instruction that contains the letter "a".

Update the documents

  1. Update each recipe document so that it contains a new field named 'howMany'
    • this field represents how many people this recipe is for

Find documents in the collection using the ingredient array

General hint: There are several ways to solve every problem. This discussion might be helpful for some of these queries, while the $elemMatch operator could also be useful.

  1. Find all recipes with the ingredient "egg".
  2. Find all recipes without the ingredient "egg".
  3. Find all recipes with the ingredient "egg" and "sugar".
  4. Find all recipes with the ingredient "egg" or "sugar".
  5. Find all recipes with exactly 3 ingredients.
    • Hint: Use the operator $size, example
  6. Find all recipes with at least 3 ingredients.

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.type").sort();

Cursors and iteration

  1. Iterate all the recipes printing the titles.

Aggregation

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


What links here