MongoDB Getting Started
In this lesson you get a MongoDB database running and send your first commands with the MongoDB Shell.
Two Ways to Get MongoDB
| Option | What you do |
|---|---|
| MongoDB Atlas (cloud) | Sign up on the MongoDB website, create a free cluster, add a database user and allow your IP address. Nothing to install on your computer. |
| Local install | Download MongoDB Community Server for Windows, macOS or Linux, and install mongosh (the shell) and MongoDB Compass (a visual tool). |
Atlas is the quickest start, and it is what most real apps use. When you add your IP address, you can choose "allow access from anywhere" while learning, but never leave that open for a real project.
Connect with mongosh
mongosh is the MongoDB Shell, a command line where you type JavaScript-style commands.
For a local server:
Example
mongoshFor Atlas, copy the connection string from the Atlas "Connect" screen:
Example
mongosh "mongodb+srv://cluster0.abcde.mongodb.net/" --username ayeshaThe prompt shows the current database, such as test>.
Databases
Show all databases:
Example
show dbsadmin 40.00 KiB config 60.00 KiB local 72.00 KiB
Switch to the institute database:
Example
use instituteswitched to db institute
The database does not really exist yet. MongoDB creates it automatically the moment you save the first document in it. That is why institute will not appear in show dbs until then.
The variable db always points to the current database:
Example
dbinstitute
Collections
Like databases, collections are created automatically when you first insert into them:
Example
db.students.insertOne({ name: "Test Student", city: "Karachi" }){
acknowledged: true,
insertedId: ObjectId('6710a1f2c3b4d5e6f7a8b900')
}Now both the database and the collection exist:
Example
show collectionsstudents
You can also create a collection yourself, which is useful for adding options later:
Example
db.createCollection("courses"){ ok: 1 }Delete a Collection or Database
Example
db.students.drop() // deletes the students collection
db.dropDatabase() // deletes the current databaseBoth return true or { ok: 1, dropped: 'institute' } when they succeed. There is no undo, so double-check which database you are in first.
Useful Shell Commands
| Command | What it does |
|---|---|
show dbs | Lists databases |
use name | Switches database (creates it on first insert) |
db | Shows the current database |
show collections | Lists collections in the current database |
db.createCollection("x") | Creates a collection |
db.x.drop() | Deletes a collection |
cls | Clears the screen |
exit | Leaves mongosh |
MongoDB Compass
Compass is MongoDB's free desktop app. You paste the same connection string, then browse databases, edit documents and build queries with buttons. It also has the shell built in at the bottom of the window.
Exercise
Exercise
You type use shop and nothing else. When does the shop database actually get created?
