Installing and shell basics
MongoDB has a server that stores data and a shell you type commands into.
- Tell the difference between the mongod server and the mongosh shell.
- Describe databases, collections and documents in one sentence each.
- Insert, read, update and delete a document with the four core commands.
- List databases with show dbs and switch with use.
In plain English
A MongoDB server is a long-running program called mongod that stores and reads your data. The shell, called mongosh, is the separate program you type commands into to talk to that server. A database holds related collections, a collection holds documents, and a document is a single record written in a JSON-like format called BSON. You do most everyday work with four commands: insertOne to add, find to read, updateOne to change and deleteOne to remove. The shell also has helpers such as show dbs and use that let you see and switch between databases.
Step by step
- 1Install MongoDB and start the mongod server on your machine.
- 2Open a new terminal and run mongosh to connect to the server.
- 3Run show dbs, then use library to switch to a database named library.
- 4Insert a document into a new books collection with insertOne.
- 5Read it back with find, change it with updateOne and remove it with deleteOne.
show dbs
use library
db.books.insertOne({
title: "The Pragmatic Programmer",
pages: 352,
tags: ["engineering", "career"]
})
db.books.find({ title: "The Pragmatic Programmer" })
db.books.updateOne(
{ title: "The Pragmatic Programmer" },
{ $set: { pages: 360 } }
)
db.books.deleteOne({ title: "The Pragmatic Programmer" })Common mistakes
- Typing mongod inside the shell is wrong; mongod is the server program and mongosh is the client you use to talk to it.
- Running use library does not create the database by itself; the database is only created when you write your first document into it.
- Using find without a filter returns every document in the collection, which is fine for a few records but not for a large one.
- Forgetting the $set operator inside updateOne replaces the whole document when you only meant to change one field.
Create a reading list
Switch to a database named library and insert a book document with title, pages and tags, then read it back with find.
use libraryWhat is the relationship between the mongod server and the mongosh shell?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.