Document database foundations
Navigate with mongosh
Connect with the current shell, select a database, inspect collections, and understand when MongoDB creates them.
The current MongoDB shell is mongosh. Start it against your local server or paste your Atlas connection string:
mongosh
# or
mongosh 'mongodb+srv://app_user:s3cretPass@cluster0.ab1cd.mongodb.net/animals'
Once connected, run db to see which database is selected. A fresh install usually shows test:
db
// test
Switch context with use animals. That selects the animals database for the rest of the session:
use animals
db.getName()
// animals
MongoDB creates a database and an ordinary collection when the first document is written. Running use animals alone does not create anything on disk yet. You can also create a collection explicitly when you need validation, capped behavior, or other options from the start.
List what exists with show dbs and show collections. After you insert your first document, the database appears in show dbs and the collection shows up in show collections. Before the insert, show dbs may still omit animals even though you ran use animals. That is normal.
The shell also keeps a history. Press the up arrow to repeat a command, and use .editor when you want to write a longer query before sending it.
Create a disposable database and inspect what MongoDB creates:
use animals
db.animals.insertOne({ name: 'Luna', age: 4 })
show collections
db.animals.find()
Run db.getName() before each destructive command. Notice that selecting animals did not persist anything until the insert. Remove the practice database only after confirming you are still connected to the local lab rather than Atlas or another shared server.
To drop the practice database when you are done:
db.getName()
// animals
use animals
db.dropDatabase()
// { ok: 1, dropped: 'animals' }
If db.getName() returns anything other than your disposable lab database, stop and reconnect before running dropDatabase().
Lesson completed