MongoDB Basic CRUD Cheat Sheet
Tags: tutorial, mongodb, beginners, webdev
Published: 2022-07-28 18:32:22

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
```sh
use starter
```
![Create new database in MongoDB](https://datmt.com/wp-content/uploads/2022/07/image-43.png)
## Collection CRUD
### Create Collections
Before inserting documents, you need to create collections. You can create a collection by:
null
Let me demonstrate
```sh
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](https://datmt.com/wp-content/uploads/2022/07/image-44.png)
### Rename collection
To rename a collection, simply call renameCollection on the collection you want to rename
```sh
# Create a wrong name collection
db.createCollection("wrong_name")

# Rename the collection
db.wrong_name.renameCollection("correct_name")
```
![Rename a collection](https://datmt.com/wp-content/uploads/2022/07/image-46.png)
### Drop collection
To remove a collection (and all documents inside), simply call:
```sh
db.create_implicitly.drop()
db.create_explicitly.drop()
```
![](https://datmt.com/wp-content/uploads/2022/07/image-45.png)
## 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
```sh
db.dogs.insert({"name": "Bingo"})
db.dogs.insert([{"name": "Pie"}, {"name" : "Borg"}])
```
![Using insert to create documents in MongoDB](https://datmt.com/wp-content/uploads/2022/07/image-47.png)
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
```sh
db.dogs.insertOne({"name": "Biscuit"})
```
![Using insertOne in MongoDB](https://datmt.com/wp-content/uploads/2022/07/image-48.png)
#### Using insertMany
Similar to insert, you can insert multiple documents using insertMany. This function accepts only array, not object:
```sh
db.dogs.insertMany([{"name": "Steven"}, {"name": "Jessica"}])
```
![Using insertMany in MongoDB](https://datmt.com/wp-content/uploads/2022/07/image-49.png)
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
```sh
db.dogs.find()
```
![](https://datmt.com/wp-content/uploads/2022/07/image-50.png)
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:
```sh
db.dogs.find({"name" : "Bingo"})
```
![](https://datmt.com/wp-content/uploads/2022/07/image-51.png)
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"
```sh
db.dogs.find({"name" : {$regex: /B.*/i}})
```
![Use find with regex](https://datmt.com/wp-content/uploads/2022/07/image-52.png)
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.
```sh
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](https://datmt.com/wp-content/uploads/2022/07/image-54.png)
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
```sh
db.dogs.updateOne(
  {name:  {$regex: /B.*/i } }, 
  { $set: { age: 8 } }
)
```
![](https://datmt.com/wp-content/uploads/2022/07/image-58.png)
#### Update multiple documents
You can use the update command to execute update on multiple documents, not just one
```sh
db.dogs.update(
  {name:  {$regex: /B.*/i } }, 
  { $set: { age: 6 } },
  {multi: true}
)
```
![Update multiple documents ](https://datmt.com/wp-content/uploads/2022/07/image-55.png)
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](https://datmt.com/wp-content/uploads/2022/07/image-56.png)
You can also use updateMany to update multiple documents without passing {mulitple: true}
```sh
db.dogs.updateMany(
  {name:  {$regex: /B.*/i } }, 
  { $set: { age: 7 } }
)
```
![Update multiple documents using updateMany](https://datmt.com/wp-content/uploads/2022/07/image-57.png)

### 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:
```sh
db.dogs.deleteOne({name: "Bingo"})
```
![Delete one document](https://datmt.com/wp-content/uploads/2022/07/image-60.png)

#### Delete all matched documents
If you want to delete all matches documents, use deleteMany
```sh
db.dogs.deleteMany({name: {$regex: /B.*/i}})
```
![Delete many documents](https://datmt.com/wp-content/uploads/2022/07/image-61.png)
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](https://datmt.com/wp-content/uploads/2022/07/image-62.png)
## 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.