Basic CRUD with MongoDB

James JingChao Yu
5 min readMay 31, 2021

--

In this week’s blog, we will explore basic CRUD (Create, Read, Update, Delete) functionalities with a MongoDB. We will first go over the installation process for MongoDB on a Mac and Windows.

If you’re on a Mac, first install Homebrew by running the command /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" from your Terminal. Once Homebrew is installed, run brew tap mongodb/brew then brew install mongodb-community@4.4 on your Terminal to install MongoDB 4.4 Community Edition.

After installation, you can start MongoDB with the command brew services start mongodb-community@4.4 and to stop MongoDB, simply type in the command brew services stop mongodb-community@4.4

To begin using the Mongo Shell, from the Menu Bar, click on Shell, New Tab to open a new Terminal tab, type in mongo and you should see the screen blow:

For Windows machine, go to this page and select to download the msi package. For there, choose Complete as Setup Type and Install MongoDB as a Service on the Service Configuration screen, the rest of the fields can be left as is.

After the installation, from your Desktop, type env in the Search Bar and choose Edit the system environment variables. Click the Environment Variables button:

From System variables, click PATH, then click on the Edit… button. From the popup pane, paste in C:\Program Files\MongoDB\Server\4.4\bin or wherever you chose to install MongoDB.

If you type mongo from the Windows Terminal or Command Prompt, you should see the MongoDB shell version number, as well as some system message stating you’re connected similar to this screen on a Mac:

That’s all for setup, let’s now explore some basic commands from the Mongo shell related to CRUD!

To show all databases:

show dbs

show dbs command shows all the databases

To create a new or switch to an existing database:

use nameOfDatabaseDB

use schoolDB in this case creates the school database, if it already exists, switch to it

If at this point you run show dbs again, you will notice our school database does not show up, that’s because it has no collections (or tables) in it, which brings us to the next command:

Create a new collection and get a list of collections

db.createCollection(‘collectionName’) and show collections

We added the students collection and get a list of the current collections

Now if you run the show dbs command, you will see our schoolDB shows up:

Now that we have a students collection to work with, let’s insert some documents (or rows) into it.

Inserting documents

db.students.insert( { field: value, field: value, field: value } )

After we call the db.nameOfCollection.insert()

Let’s insert a few more students into our collection, but this time, we will use the insertMany to insert multiple documents:

Inserting multiple documents

db.students.insertMany([{student1Obj}, {student2Obj}, {student3Obj])

After we inserted 3 more students

As you can see, the first student has an address field (or column) that’s missing from the newly created three students, but we still successfully inserted them into our collection.

We can retrieve all entries with the following two commands:

Show all documents

db.nameOfCollection.find() or db.nameOfCollection.find().pretty()

Calling the pretty() after find() will show the entries in a formatted output

To search for a specific student or students, we can put an argument within the find() command:

Search for a particular document

db.students.find( { field: value } )

For example, if we were trying to find the students who majors gaming:

We get our two results back

To update a specific field, we use the update() command:

Updating or replacing a field

db.students.update( {name: ‘james’}, { $set: {field: value} })

If you put in a field that did not exist, Mongo will simply create that field. Let’s say we try to update the student with the name ‘James’ and give it a title like so:

The title field is added after our operation

To replace a whole document (or row), simply leave out the $set like so:

The address and title fields are gone

To delete a single field (column), such as name, age or grade in our example, we can use this command:

Deleting a field

db.students.update( {field: value}, { $unset: {age: “”} })

Renaming a field

To rename a field, use the $rename command

The grade field is renamed to gpa

Deleting a document

To delete a document (row), simply call the remove command like so:

db.students.remove( {field: value} )

After deletion, we call the length() command and it correctly returns 3, which is the number of documents we have so much.

Let’s now create a teachers collection and see how we can delete it.

Drop a collection

To drop (delete) a collection, we call db.nameOfCollection.drop() command

After we drop the teachers collection

Drop a database

And finally, we can drop the whole schoolDB. First we call the db command to make sure we are within the school database, then we can drop it with db.dropDatabase() command.

After we drop the schoolDB

Next week we will explore more CRUD functionalities of MongoDB and see how it works with a Rails application. See you next week!

--

--

No responses yet