Learn MongoDB: CRUD Basics

paras594

Paras 🧙‍♂️

Posted on October 3, 2020

Learn MongoDB: CRUD Basics

This is the continuation of my previous post, where I explained how to install and setup mongodb and some basic commands. In this post, I will be covering basic CRUD operations. So fire up your shell and let's get started !

Table of content:

Working with Database

Database will contains all your collections(tables in sql). We will create a database named pokeworld in this post and it will have collections like pokemons, trainers etc.

Create Database

> use pokeworld
Enter fullscreen mode Exit fullscreen mode

Check the db in use

> db
#or
> db.getName()
Enter fullscreen mode Exit fullscreen mode

Drop db

> db.dropDatabase()
Enter fullscreen mode Exit fullscreen mode

Get db stats

> db.stats()
Enter fullscreen mode Exit fullscreen mode

Get info about collections in db

> db.getCollectionInfos()
Enter fullscreen mode Exit fullscreen mode

Working with Collections

Collections hold documents together. They are similar to tables in sql. E.g. Just like in sql we can have a table or users with fields such as name, age, gender, occupation etc. we can have a collection of users where documents(JSON-like) can have those fields as well in key value pairs.

Example document:

{
   name: "John",
   age: 20,
   gender: "male",
   occupation: "engineer"
}
Enter fullscreen mode Exit fullscreen mode

CRUD operations are also carried on collections. So, most of our work will revolve around collections from now on. We will create some collections in our pokeworld db and learn some useful methods related to them.

Create Collection

In mongo, collections are automatically created when adding data to a non-existing collection. But to create them explicitly, use the following method:

> db.createCollection("pokemons")
Enter fullscreen mode Exit fullscreen mode

Show Collections in db

> show collections
# or
> db.getCollectionNames()
Enter fullscreen mode Exit fullscreen mode

Drop a Collection

> db.pokemons.drop()
Enter fullscreen mode Exit fullscreen mode

Rename a Collection

> db.pokemons.renameCollection("pokemons-renamed")
Enter fullscreen mode Exit fullscreen mode

Check Collection Stats

> db.pokemons.stats()
Enter fullscreen mode Exit fullscreen mode

Count docs in collection

> db.pokemons.count()
Enter fullscreen mode Exit fullscreen mode

CRUD Operations

All the operations that we need for creating, reading, updating & deleting are available on collection. Let's see the basic and most used operations you need.

Create

There are two methods that we need to create documents in collection.

  • insertOne
  • insertMany

Why not add data to our pokemons collection in pokeworld db.

# insert one pokemon 
> db.pokemons.insertOne({
    name: "Pikachu",
    type: "Electric",
    health: 35
})

# insert more than one pokemon at once
> db.pokemons.insertMany([
    { name: "Squirtle", type: "Water", health: 44 },
    { name: "Poliwag", type: "Water", health: 40 },
    { name: "Bulbasaur", type: "Grass", health: 45 },
    { name: "Pidgey", type: "Flying", health: 40 }
])
Enter fullscreen mode Exit fullscreen mode

Read

For reading data from our collection, we can just need two methods. These methods have several operators and options that can help us filter our data according to our needs.

  • find: returns multiple documents
  • findOne: returns the first document only

In these two operations, we can pass filters. If no filter passed, it will return all the documents in case of find and first document in case of fineOne

# find one 
> db.pokemons.findOne({ name: "Pikachu" })

# find all water type pokemons
> db.pokemons.find({ type: "Water" }) 

# find pokemons with health greater than 40
> db.pokemons.find({ health: { $gt: 40 } })

# find pokemons with type water and health greater than 40
> db.pokemons.find({ type: "Water", health: { $gt: 40 }})
Enter fullscreen mode Exit fullscreen mode

In the above example, there is $gt operator that we used. There are other operators and we will discuss in later posts.

Update

Again, we have two methods for updating documents

  • updateOne
  • updateMany

Both takes a filter, just like find, to find the document that we need to update, and an object that defines what we want to update. We use $set operator to update fields in a document.

# update one pokemon
> db.pokemons.updateOne(
    { name: "Pikachu" },
    { $set: { health: 45 }}
)

# update multiple pokemons and add weakness to water types
> db.pokemons.updateMany(
    { type: "Water" },
    { $set: { weakness: "Electric" }}
)

# increment health of pikachu by 10 and also add weakness
> db.pokemons.updateOne(
    { name: "Pikachu" },
    { 
       $inc: { health: 10 },
       $set: { weakness: "Ground" }
    }
)
Enter fullscreen mode Exit fullscreen mode

In above examples, you can see, we can change multiple fields in one update. $inc is one operator you see here that we can use to increment/decrement Number types. There are other operators that we will discuss later.

Delete

Our last operation is Delete.

  • deleteOne
  • deleteMany

Both are similar to update and find methods. They take a filter to identify the document that we want to delete. Let's see some examples:

# delete one pokemon
> db.pokemons.deleteOne({ name: "Pikachu" })

# delete pokemons with health greater than or equal to 40
> db.pokemons.deleteMany({ health: { $gte: 40 }})

# delete all pokemons !!
> db.pokemons.deleteMany({})
Enter fullscreen mode Exit fullscreen mode

Sad :( We deleted Pikachu. Don't forget to add him back.

But that's how delete methods work. As you can see, it is similar to finding the document or documents. If you can find it, you can delete it. In the above example we used an operator $gte. It stands for greater than equal. And you can see how it is used to query data.


So, that's it for this one. Next, we will take a deeper look into read operations. More ways to filter data, available operators, etc.

Happy Coding :)

Next Post : Query Documents - Part I

Prev Post : Getting Started

💖 💪 🙅 🚩
paras594
Paras 🧙‍♂️

Posted on October 3, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

GETTING STARTED WITH MONGODB
mongodb GETTING STARTED WITH MONGODB

September 13, 2021

Learn MongoDB: Getting Started
mongodb Learn MongoDB: Getting Started

October 3, 2020

Learn MongoDB: CRUD Basics
mongodb Learn MongoDB: CRUD Basics

October 3, 2020