MongoDB

Stage 2 of 8 · 9 lessons · ~2 weeks

Reading and writing documents

Insert, find, update and delete documents in mongosh: filter with query operators, shape results with projection, sort and limit, change fields with update operators, and know when to upsert or replace.

Start: Inserting documents

Lessons· one lesson for each topic, in this order

  1. 1Inserting documents
  2. 2find, findOne and equality filters
  3. 3Comparison and logical query operators
  4. 4Projection: choosing the fields you get back
  5. 5Sorting, skip, limit and cursors
  6. 6updateOne, updateMany and update operators
  7. 7Upserts
  8. 8Replacing versus updating
  9. 9Deleting documents safely

Do this

  • Insert single documents and a batch, and read the returned ids.
  • Write filters with ranges, $in, $or, $exists and $ne, predicting the count first.
  • Add projections to every list query you write.
  • Write a paginated query with sort, skip, limit and a tie-breaker.
  • Update fields with $set, $inc and $unset and check matchedCount and modifiedCount.
  • Write an upsert with $setOnInsert.
  • Run the count-first routine before a deleteMany.

Start with

  • CourseFree
    MongoDB University

    MongoDB

    Free: the CRUD lessons on inserting, finding, replacing, updating and deleting documents, with labs

Practise

  • Test filters and updates on your own sample documents and share the link when you get stuck

Keep handy

Before moving on: A saved mongosh script of 30 working commands against your sample dataset, each with a comment stating the question it answers or the change it makes, including range filters, a projection, a paginated query, update operators, an upsert and a counted delete.

Tauseef's advice
Before you run a query, guess how many documents it will return, and before you run an update or delete, count what the filter matches. Predicting and then checking catches more bugs than any tool, and it is the habit that stops you wiping a collection on a Friday afternoon.

Mark this stage as not done?