Getting started with MongoDB

Madhavi Imashi
6 min readMay 15, 2022

Hey there! Are you looking for a simple guide to using MongoDB in your project for the first time or as a beginner? You’re at the right blog post. I’ll be giving you a comprehensive understanding of the specialty in MongoDB compared to other database options & most importantly will walk you through the basic commands that you need to be knowing when you’re trying out things with MongoDB as a beginner with practical examples.

Why Mongo DB is easy in terms of managing and handling data?

  • You can use your favorite javascript support IDE to try out queries, unlike other database management systems.
  • If you know javascript basics, It’s very easy to get used to Mongo DB commands since it has some similarities. (why because MongoDB is a javascript running environment)
  • No fixed schema is required(no specifically designed structure is needed when creating database collections in MongoDB)
  • mongo shell is very easy to use. Also if you want some kind of a GUI to write queries there are multiple options for that as well. MongoDB Compass is an example that I think is a good one that has an auto-complete feature which makes our job easy as well.
  • the most interesting part is, that in MongoDB, data is stored as documents.
Example for a Document in a MongoDB collection
  • As in the above example, all the documents are stored in JSON (JavaScript Object Notation) format.

Comparison between a relational DB and MongoDB(non-relational)

A simple diagram that elaborates the difference between a relational DB and MongoDB

Alright now that we know some of the coolest features in MongoDB why not we give it a try to explore it.

Time to try the MongoDB commands

In a moment, I’m gonna be giving a summary of all the important and basic commands that you should know when dealing with MongoDB. The best thing I would suggest is to install Mongo DB without any delay and try out these commands by yourself to get a hands-on experience that you’ll not regret at the end of the day. Trying things on your own is always more efficient and stays in your memory much longer rather than learning a hell lot of theories back to back. so let’s jump into it without further a duo.

By following the steps given in the installation guide of MongoDB documentation, now you might have installed MongoDB into your computer according to the operating system that you have. Before moving on to the next step, make sure that you have started MongoDB running.

As I said earlier, you have multiple options to try out queries in mongo DB

  • You can use your command prompt/ zsh to try everything without any obstruction.
  • Or you can use your preferred IDE (ex: VScode)
  • Or else u can use a GUI desktop application like MongoDB compass.

The choice is yours.

Just to give you an idea of how it will look like and what is so different in using either one of them, here I’ll attach some screenshots of how it looks like when using all 3 interfaces.

(mac OS terminal)
(VS Code terminal)
(MONGOSH in MongoDB Compass)

So as you can see, if you’re using a CLI, you can start the mongo shell by executing the following command in the terminal that you use.

 mongosh

Alright then, now it’s time to explore the mongo DB commands.

  • Show all existing databases in the current instance of MongoDB
show dbs
  • Create a new DB or use an existing DB
use <dbName>Ex: Create a DB or go to existing DB with the name 'test-db'.use test-db
  • Drop an existing DB
Go to that DB( use <dbName> ) & execute:db.dropDatabase()

CREATE

  • Insert a document(A document is similar to a single record of data in a relational DB table)
db.<collectionName>.insertOne()Ex: Insert new friend object(document) to the friends collectiondb.friends.insertOne({ name: “Imashi”, BOD:  “1999–01–07” })
  • Insert multiple documents at once into a specific collection
db.<collectionName>.insertMany()Ex: Insert two documents into friends collectiondb.friends.insertMany(
{
name: “Imashi”,
BOD: “1999–01–07”
},
{
name: “Heli”,
BOD: “1999–04–22”
}
)

(Here the special thing is, once you've created a DB, you can create a new collection and start inserting data/documents to the collection both with just one command )

READ

  • Retrieve all documents in a specific collection
db.<collectionName>.find()Ex: db.friends.find()
  • Find by filtering
db.<collectionName>.find(<filterCriteria>)Ex: Get all friends with the last name ‘Fernando’db.friends.find({ lastName: “Fernando” })
  • Find by equal ($eq) parameter
Ex: Get all friends with the last name ‘Fernando’db.friends.find({ lastName: {$eq: “Fernando”} })
  • Find by not equal ($ne) parameter
Ex: Get all friends except the friends whose last name is ‘Fernando’db.friends.find({ lastName: {$ne: “Fernando”} })

Just like $eq and $ne, there are more parameters such as $gt (greater than), $lt (less than), $lte (less than or equal to), $or(check that one of multiple conditions is true), $and(check that all conditions are true). Check out the documentation for more.

  • Retrieve data by limiting to a specific no of results
limit(<no-of-documents>)Ex: Get only the first 2 documents(objects) in the friends collectiondb.friends.find().limit(2)
  • Sort the results by a specific criteria
sort(<sorting-criteria>)Ex: Get all friends sorted by name in alphabetical orderdb.friends.find().sort({ name: 1})

UPDATE

  • Update a particular document in a specific collection
db.<collectionName>.updateOne(<filter-criteria>, <update-object>)Ex: Update the first document(friend) with an age of 19 to the age of 20.

db.friends.updateOne({age: 19}, {$set: {age: 20} })
  • Update all documents that matches with the filter criteria.
db.<collectionName>.updateMany(<filter-criteria>, <update-object>)Ex: Update all friend objects(documents) with an age of 19 to the age of 20.

db.friends.updateMany({age: 19}, {$set: {age: 20} })
  • Replace an entire document with a new object
db.<collectionName>.replaceOne(<filter-criteria>, <new-object>)Ex: Replace the first document(friend) with an age of 30 to an entire new object as 
{
name: "Kamal",
age: 31,
description: "oldest friend of me"
}

db.friends.replaceOne({age: 30}, {name: "Kamal", age: 31, description: "oldest friend of me"})

DELETE

  • Delete a particular document in a specific collection
db.<collectionName>.deleteOne()Ex: Delete the first document(friend object) with the name 'Imashi'.

db.friends.deleteOne({ name: “Imashi” })
  • Delete all documents that matches with the filter criteria.
db.<collectionName>.deleteMany()Ex: Delete all friend objects(documents) with a last name 'Fernando'

db.friends.deleteMany({ lastName: “Fernando” })

At last,

  • If you want to clear the terminal -> cls
  • To terminate mongosh from the terminal -> exit
  • To start mongo shell again -> mongosh

Now that you know some of the basic yet the most important commands, don’t forget to explore more from the MongoDb documentation which I see as comprehensive documentation compared to the documentations available for other different DBMSs.

So go explore & have fun. Cheers!

--

--