Getting started with the MongoDB shell.

ham_codes
2 min readJan 3, 2021

I’ve been recently learning the ins and outs of MongoDB. Reading the documentation really helped when learning how to install mongo and when I wanted to get good with the database I learned as much about the mongo shell as I could. What is the mongo shell? According to the official documentation from “https://docs.mongodb.com/manual/mongo/“, “The mongo shell is an interactive JavaScript interface to MongoDB. You can use the mongo shell to query and update data as well as perform administrative operations.” I have been working with JavaScript for a while now so the fact that the mongo shell had an interactive JavaScript interface really made the transition to learning MongoDB a little easier.

The mongo shell comes as part of the installation with MongoDB and is installed in the same location. There are ways to download the shell as a stand alone but I use the shell with the entire MongoDB package. In order to launch the mongo shell, an instance of the mongo server must be up and running. While I am in my terminal I can simply type the command “mongo” and here I go. There are many options when loading the shell which can be found in the documentation on the MongoDB official site. If you want to see the current database you’re working with, simply type in “db”. To switch to a different database simply type the command “use <database>”. Now we can perform some CRUD (create, read, update and delete) operations in our mongo shell. Let’s first look at creating or inserting a document. Let’s say we’re working with a collection database. In order to insert a document we have two options, one is db.collection.insertOne() which inserts a single document, or db.collection.insertMany() which inserts multiple documents. So if we were inserting a document into our inventory database we could do that by the following command db.inventory.insertOne({ item: “book”, quantity: 1 }) Next let’s update our inventory database by typing db.collection.updateOne() or db.collection.updateMany(). How about removing some of these documents from the database? Simply typing in db.collection.deleteOne() or db.collection.deleteMany() will take care of this for us. Want to delete the book we created earlier? We can do that by db.inventory.deleteOne( { item: “book” } ).

This is a basic overview of only some of the many operations that can be performed in the mongo shell. The documentation is very detailed and can answer any question that a developer could have. Below are some resources that can be very helpful in getting started with the mongo shell. Thanks for reading and have a great day!

https://blog.codecentric.de/files/2012/12/MongoDB-CheatSheet-v1_0.pdf

--

--