You will learn all the most important commands and queries in order to know how to handle by yourself MongoDB database.

This will become your index, as is organized to be as simple as possible so you can use to get back and easily remember that command that you need.

This will not show how to install or open, please try look into the internet it's really simple.

Let's dive into, this is the list of commands that you will learn.

Create database / select.

Check which database is selected.

See all your databases.

Show your collections / db's.

Delete your collection.

Drop selected database.

Create collection.

Capped option *(for create collection).

Insert Data.

Data.

Updating.

Find / query.

Removing data.

Projection.

Limit.

Sort.

Create database / select.

Create Database / Select, right: use "DATABASE NAME"

*If database doesn’t exist, will be created and selected

Check which database is selected.

To check the current selected database just type: db

See all your database.

To see all databases type: show dbs

*There’s a trick, you may not see you database, this is because is “empty”, only after you add something inside (document) that will be shown

Add some data in the database, use this command: db."any name that will represent your collection".insert("data that you want, for example {"name":"xcv"}")

Example: db.names.insert({"name":"zxcvb"})

*If you have not selected any db the ‘test’ one will be automatically selected.

Now type again: show dbs and your database will be shown.

Show your collections / db.

Show your db collections (the one that you have selected), type: show collections

Delete your collection.

To delete your collection type: db."name of your collection".drop()

For example: db.names.drop()

Doing this and type again to see your collections, will be gone.

Drop selected Database.

To drop your selected database, delete first make sure you are using the database that you want to delete / drop, and type: db.dropDatabase()

Now type again: show dbs and will be gone:

Create Collection

Create custom collections with parameters and options:

For this, we can use the command db.createCollection("name", "options")

For the options we have: createCollection

For option, we have different ones, but I will show one very important, that is the capped option.

Capped option means that a fixed-sized collection that automatically overwrites its oldest entries when it reaches its maximum size.

When you create using the capped option this means that you will say that this has a size, it's mandatory if you specify this option.

Capped

Capped works like a stack, this means that when you specify a size, and you reach this size, the oldest one will be deleted automatically.

Size is bits, for be more simple to visualize we will set to the key max, which is maximum items that can be added there.

Let’s try this: db.createCollection("tags",{capped:true, size:1000, max:2})

We are creating a collection that the maximum size is 2 items, so if I add more than this should remove the oldest one automatically.

Just add two data into for example like this: db.tags.insert([{"database":["mysql", "postgresql","mongodb"]},{"mongodb":"nosql"}])

If you see, now we have something like this:

Now if you add one more item one item will drop from the collection, as we told at the beginning that the maximum size should be 2.

For example, add: db.tags.insert({"database":"no data"}) , and after print your collection you will have this:

As you can see, MongoDB automatically dropped one item, as we set that the maximum amount of items is 2. If bu some reason the size reaches first, I don’t know some huge item is added, them, size will have precedent over max.

Insert Data.

Insert data into your collection, use this syntax db."collection name".inset("document")

For example, assume that you have a collection called posts:

db.posts.insert({title:"Learning mongodb commands",description:"tutorial explaining the basic and most know for mongodb", tags: ['mongodb', 'database', 'NoSQL'], likes:100 })

To check your added data type: db.posts.find() this will list all the documents inside this collection:

As you can see, we have one ‘_id’, you can provide your own, and if not mongo will create one for you.

*Tip: To show a better visual / representation, add pretty() at the end, like: db.posts.find().pretty()

Updating.

One command that needs to be shown right after is, how do I update my data? There are 2 basic ways, one is updating the entire data, or just update one field.

First, let’s update the entire data, we will use the command update() , this command had two basic arguments, the selection criteria, and the data to be updated.

Updating our post using our ID:

db.posts.update({_id:ObjectId("5dbd5217f54d77cc13fbdb47")}, {"title" : "Learning advanced mongodb commands", "description" : "Version 2 explaining the basic and most know for mongodb", "tags" : [ "mongodb", "database", "NoSQL", "updating"], "likes" : 500 })

This will be the result:

If you list again your data you will see that is updated:

Another way to update is just updating one item, for this we will use again the ‘_id’ as a query to select our post, and will remove some queries:

db.posts.update({_id:ObjectId("5dbd5217f54d77cc13fbdb47")}, {$set: {"tags" : [ "mongodb", "NoSQL"]}})

This is the result:

Printing the data again you should have something like:

Find / Query.

Now let’s go to how to query data, we kind already saw something, that was .find()

Assuming that you have data, let’s search, for now, I have the only one that I added, I will add two more, you can use this:

db.posts.insert([{"title" : "More commands", "description" : "have more command for inserting data into", "tags" : [ "mongodb", "moredata", "NoSQL" ], "likes" : 200 }, {"title" : "Advance commands", "description" : "very advanced commands for MongoDB", "tags" : [ "mongodb", "NoSQL", "database" ], "likes" : 1000 }])

You will see something like this, remember that we are not setting the ‘_id’ so, will be automatically added.

This will add 2 more data, as you can see, to add more data you only need to add using an array.

Here we will have many commands, we have basically two, one is the find() that we saw that if there's no operation to compare return all, and another one findOne() that as you imagine only return one.

In MongoDB our queries actually are documents, or we can simplify as a JSON, this is how we can add queries with an operation to be validated and return, let’s try a simple one:

If you added the same data, just try: db.posts.find({title:"More commands"}).pretty() .

*Remember that ‘pretty()’ it’s just for look better is not needed.

This command search for the title that matches that exact value, now let’s try more two, Less Than and Less Than Equals:

Less Than: db.posts.find({"likes":{$lt:500}}).pretty()

We have just one, now let’s try another, Less Than Equals: db.posts.find({"likes":{$lte:500}}).pretty()

As you can see now we see two items and not only one as we evaluate if is less or equal.

We have the same “variant” but for bigger than would be respectively:

Greater Than: db.posts.find({"likes":{$gt:500}}).pretty()

Greater Than Equal: db.posts.find({"likes":{$gte:500}}).pretty()

And Not Equals: db.posts.find({"likes":{$ne:500}}).pretty() that will show the only one that is not equal to that.

This is basically for one validation, but we can have more using “AND” for instance would be:

For example: db.posts.find({$and:[{"likes":{$gt:200}}, {"likes":{$lte:1000}}]}).pretty()

Another variant will be “OR”, we follow the same pattern but using OR:

For example: db.posts.find({$or:[{"likes":{$lt:50}}, {"likes":1000}]}).pretty()

As you see only return the one that has likes equal to 1000 as have no match for less them 50.

Removing Data.

Removing data, for this is simple like find and updating, the syntax is simple: db.posts.remove("Document criteria that you want to remove")

For example: db.posts.remove({"title":"Advance commands"})

Projection.

Projection, on MongoDB you the biggest difference between “normal” database is that it is a cheaper duplicate, like, have more data in the disk than optimize itself to have the best “alignment” in order to be better in the future to retrieve.

Saying that we most probably will have NoSQL database with big “tables”, but, if you want to return some data, not the entire “columns” for instance, there’s where Projection comes in place.

In short term you will specify which value/data you actually want to be returned, like, you will have your “find” query, but only the data that you specify will be returned, for example: db.posts.find({},{_id:0,title:1,tags:1}).pretty()

And this will be the result:

What we did, we just used the normal find to search for data, we said first that we want all data using "{}" this mean that I'm not using any filter, then, we specify which data we want to show, this is done by saying 0 or 1 this is basically false or true, if you notice we said, don't return "***_id***" as by default always came, and said give me only "title" and "tags" and this is it, this is the data that came.

Limit.

You can specify the limit of items that will be returned to you, one way of doing this is after the find the query you use the limit() that you want, just setting like this: db.posts.find().limit(10) and do you will limit the result to "10".

Sort.

This is to sort as the name says, and it’s pretty much the same syntax as projection, the difference is we have sort in ascending order that is set by using number “1” and descending order that is set setting “-1”, using the syntax sort({<#key#>:<#option#>})

For example: db.posts.find().sort({likes:1}).pretty()

That's it, now you can do most of the commands that you will need in order to use this database, comparing with other database's that use SQL queries you can see how much simple it's right?

Conclusion

I hope you liked this, and if you have any comments please share them with me, if you want to ask for something, let me know, and please, hit the “clap” button as this helps deliver this content to more people.

Please share as most as possible as this helps me reach more people and continue writing, found any mistake? Get in touch let me know!

Also, I started a new channel on YouTube, I want to teach in videos what I write about, so please, subscribe if you liked this tutorial.

Youtube channel: https://www.youtube.com/channel/UC6FlmTDymN19ZWDN5jsnamA

Twitter: @ProgrammerPath

Linkedin: https://www.linkedin.com/in/felipeflorenciodev/?locale=en_US