MongoDB Basic CRUD Cheat Sheet

If you have been doing software development for some time, you’d probably know what CRUD is. CRUD stands for CREATE-READ-UPDATE-DELETE. Those are the day to day task we do on databases, regardless of their types.

Let’s get started by using a new database. As you may remember from the previous post, there is no “create” command in MongoDB. We simply use the use command. I’m going to call my new database starter

use starter
Create new database in MongoDB
Create new database in MongoDB

Collection CRUD

Create Collections

Before inserting documents, you need to create collections. You can create a collection by:

  • Assuming it exists
  • Create it explicitly

Let me demonstrate

db.createCollection("create_explicitly")
db.create_implicitly.insert({})

On line 1, I called the createCollection explicitly and gave that function a name.

On line 2, I assumed the collection named create_implicitly exist and inserted an empty document.

In both cases, the collections were created successfully

Two ways to create a MongoDB Collection
Two ways to create a MongoDB Collection

Rename collection

To rename a collection, simply call renameCollection on the collection you want to rename

# Create a wrong name collection
db.createCollection("wrong_name")

# Rename the collection
db.wrong_name.renameCollection("correct_name")
Rename a collection
Rename a collection

Drop collection

To remove a collection (and all documents inside), simply call:

db.create_implicitly.drop()
db.create_explicitly.drop()

Document CRUD

In this section, we are going to learn how to do basic CRUD on documents

Create document

You have three functions to create documents in MongoDB. They are insert, insertOne and insertMany

Using insert

db.dogs.insert({"name": "Bingo"})
db.dogs.insert([{"name": "Pie"}, {"name" : "Borg"}])
Using insert to create documents in MongoDB
Using insert to create documents in MongoDB

As you can see, you can insert one document or many documents using insert.

Using insertOne

As the name suggest, insertOne inserts only one document. Thus, it accepts only objects, not array

db.dogs.insertOne({"name": "Biscuit"})
Using insertOne in MongoDB
Using insertOne in MongoDB

Using insertMany

Similar to insert, you can insert multiple documents using insertMany. This function accepts only array, not object:

db.dogs.insertMany([{"name": "Steven"}, {"name": "Jessica"}])
Using insertMany in MongoDB
Using insertMany in MongoDB

You may wonder, what are the differences between insert and insertOne and insertMany?

Take a look at the screenshots, return types are different.

Read Documents

Now we have some documents, let’s try getting them

Using find

The most common way to retrieve documents in MongoDB is using find

db.dogs.find()
Using find in MongoDB

You can pass a filter object to the find function to get exactly what you need.

For example, finding the dog with name “Bingo” looks like this:

db.dogs.find({"name" : "Bingo"})
Using simple matching in the find function

You are not limited to exact matching. For example, you can use regex to search for documents.

Let’s find all the dogs with names begin with “B”

db.dogs.find({"name" : {$regex: /B.*/i}})
Use find with regex
Use find with regex

There are many other powerful queries you can do with find. However, that’s a topic for another post. We only do basic CRUD here.

Update documents

In the update command, you need to specify the query to get the matched documents and the operation you want to do on those documents.

Update one document

You can update a document by using its ObjectId.

db.dogs.update(
  {_id:  ObjectId("62e2533531ed3d24b2e3e0df") }, 
  { $set: { age: 5 } }
)

In this example, I knew that the dog named “Bingo” has that specific ObjectId. So, I passed that in the query object and operate the $set operation on its age field. I queried the dog “Bingo” again, I could see the age field is set to 5.

Update a document by ID

Update a document by ID

In case your query returns multiple documents and you only want to update the first one, use updateOne or update

db.dogs.updateOne(
  {name:  {$regex: /B.*/i } }, 
  { $set: { age: 8 } }
)

Update multiple documents

You can use the update command to execute update on multiple documents, not just one

db.dogs.update(
  {name:  {$regex: /B.*/i } }, 
  { $set: { age: 6 } },
  {multi: true}
)
Update multiple documents
Update multiple documents

As you can see, I needed to set {multi: true} to update multiple documents. By default, the update function only updates one record.

If I try to find all the dogs with name starts with B, I can see they all have age set to 6:

Viewing result after update
Viewing result after update

You can also use updateMany to update multiple documents without passing {mulitple: true}

db.dogs.updateMany(
  {name:  {$regex: /B.*/i } }, 
  { $set: { age: 7 } }
)
Update multiple documents using updateMany
Update multiple documents using updateMany

Delete documents

Similar to update, you also need to write a query to find the matched documents and call delete on them.

Delete one document

Use deleteOne to delete one document from the list of matches. That means, even if you have more than one document, there is only one will be deleted:

db.dogs.deleteOne({name: "Bingo"})
Delete one document

Delete all matched documents

If you want to delete all matches documents, use deleteMany

db.dogs.deleteMany({name: {$regex: /B.*/i}})
Delete many documents

In the example above, I first find the dogs that have names start with B. As you can see, there were two result.

After issuing the deleteMany query, none was found.

Delete all documents

If you want to delete all documents in a collection, simply call deleteMany passing and empty filter object. This is similar to the command TRUNCATE in SQL databases.

Delete all documents in MongoDB
Delete all documents in MongoDB

Conclusion

In this post, I have listed some of the most common CRUD commands in MongoDB. The list is far from comprehensive but it is a good start for people who have just learned this NoSQL database.

Leave a Comment