Course Outline (Part 6)

Almost every software application in the world—from Twitter to Amazon—is built around four core actions: Create, Read, Update, and Delete. In the database world, we refer to this as CRUD.

In this module, we will learn how to perform all of these operations using the MongoDB Shell. To follow along, make sure you have your shell open and are connected to your database!

First, let’s create a new database for our practice data. In your shell, type:

use library

1. Create (Insert Documents)

In MongoDB, we create data by “inserting” documents into a collection.

Insert One Document

To add a single document, we use the insertOne() method. The method takes a single JSON object.

Let’s add a book to the books collection:

db.books.insertOne({
  title: "The Hobbit",
  author: "J.R.R. Tolkien",
  pages: 310,
  isAvailable: true
})

Note: We never explicitly created the books collection. MongoDB automatically created it the moment we inserted the first document!

If successful, MongoDB will respond with an acknowledged: true message and the unique _id it automatically generated for the book.

Insert Multiple Documents

Inserting documents one by one is slow. If you have an array of documents, you can insert them all at once using insertMany().

db.books.insertMany([
  { title: "1984", author: "George Orwell", pages: 328, isAvailable: false },
  { title: "Dune", author: "Frank Herbert", pages: 412, isAvailable: true },
  { title: "Foundation", author: "Isaac Asimov", pages: 255, isAvailable: true }
])

2. Read (Find Documents)

Now that we have data in our database, let’s learn how to retrieve it. We use the find() method for this.

Find All Documents

To retrieve every single document in a collection, you use find() and pass it an empty object {} (or just pass nothing at all).

db.books.find()

This will print out all four books we just inserted, complete with their auto-generated _id fields.

Find Specific Documents

To filter your search, you pass a query object into the find() method.

Let’s find the exact book written by George Orwell:

db.books.find({ author: "George Orwell" })

Let’s find all books that are currently available to borrow:

db.books.find({ isAvailable: true })

Projection (Filtering Fields)

Sometimes a document has 50 fields, but you only want to see the title. You can use Projection to tell MongoDB exactly which fields to return.

The projection object is passed as the second argument to find(). A 1 means include it, and a 0 means exclude it.

// Give me all books, but ONLY show the title and author
db.books.find({}, { title: 1, author: 1 })

Note: The _id field is always included by default unless you explicitly set it to 0 ({ _id: 0, title: 1 }).

Sorting

You can order your results alphabetically or numerically using the sort() method. A 1 sorts in ascending order, and a -1 sorts in descending order.

// Sort all books by pages, from shortest to longest
db.books.find().sort({ pages: 1 })

Limiting Results

If you have a million books, you don’t want the database to return all of them at once. You can limit the results using limit().

// Return only the first 2 books it finds
db.books.find().limit(2)

Skipping Documents

Skipping is highly useful for creating “Pagination” (e.g., Page 1, Page 2) on a website.

// Skip the first 2 books, and return the rest
db.books.find().skip(2)

You can chain these methods together!

// Get the 3rd and 4th longest books
db.books.find().sort({ pages: -1 }).skip(2).limit(2)

3. Update (Modify Documents)

Data changes over time. When a user checks out a book, we need to update its status.

Update One Document

To update a single document, we use updateOne(). It requires two arguments:

  1. The Filter: How to find the document.
  2. The Update Operator: What to change.

We must use the $set operator to tell MongoDB exactly which fields to change. If you don’t use $set, you might accidentally overwrite the entire document!

// Find "1984" and change isAvailable to true
db.books.updateOne(
  { title: "1984" }, 
  { $set: { isAvailable: true } }
)

Update Multiple Documents

If we want to change many documents at once, we use updateMany().

Let’s say the library is closed for renovations, and we want to make all books unavailable:

db.books.updateMany(
  {}, // Empty filter targets ALL documents
  { $set: { isAvailable: false } }
)

Replace a Document

Sometimes, instead of updating specific fields, you just want to completely overwrite the old document with a brand new one. You can use replaceOne().

db.books.replaceOne(
  { title: "Dune" },
  { title: "Dune", author: "Frank Herbert", pages: 412, isAvailable: false, edition: "Special Anniversary" }
)

Note: The _id remains the same, but the rest of the document is entirely replaced by the new object.


4. Delete (Remove Documents)

Finally, let’s look at how to remove data.

(Warning: Deleted data in MongoDB is gone forever unless you have a backup strategy in place!)

Delete One Document

To delete a single document, use deleteOne(). It deletes the first document that matches the filter.

db.books.deleteOne({ title: "The Hobbit" })

Delete Multiple Documents

To delete many documents at once, use deleteMany().

Let’s delete every book that is shorter than 300 pages. We will use a special Query Operator ($lt for Less Than) which we will cover in depth in the next module!

db.books.deleteMany({ pages: { $lt: 300 } })

Delete Everything

To completely wipe out all data in a collection while leaving the collection itself intact, pass an empty filter:

db.books.deleteMany({})

Summary

You have officially mastered the basics of CRUD! You now know how to:

  • Create: insertOne(), insertMany()
  • Read: find(), sort(), limit(), skip(), and Projection.
  • Update: updateOne(), updateMany(), replaceOne(), and the $set operator.
  • Delete: deleteOne(), deleteMany()

In Module 6, we will dive deeper into the “Read” operation and unlock the immense power of Query Operators, allowing us to search our data with incredible precision.

Discussion

Loading comments...