top of page

All Basics of MongoDB

MongoDB is a rich open-source document-oriented and one of the widely recognised NoSQL database. It is written in C++ programming language.


Today, I wanted to share some of the basic stuff about MongoDB concepts and commands


Important Terms


Database

Database is a physical container for collections. Each database gets its own set of files on the file system. A single MongoDB server typically has multiple databases.


Collection

Collection is a group of documents and is similar to an RDBMS table. A collection exists within a single database. Collections do not enforce a schema. Documents within a collection can have different fields.


Document

A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection’s documents may hold different types of data.


Data Types

(Reference: tutorialsPoint)

MongoDB supports many datatypes such as:

  • String − This is the most commonly used datatype to store the data. String in MongoDB must be UTF-8 valid.

  • Integer − This type is used to store a numerical value. Integer can be 32 bit or 64 bit depending upon your server.

  • Boolean − This type is used to store a boolean (true/ false) value.

  • Double − This type is used to store floating point values.

  • Min/ Max keys − This type is used to compare a value against the lowest and highest BSON elements.

  • Arrays − This type is used to store arrays or list or multiple values into one key.

  • Timestamp − ctimestamp. This can be handy for recording when a document has been modified or added.

  • Object − This datatype is used for embedded documents.

  • Null − This type is used to store a Null value.

  • Symbol − This datatype is used identically to a string; however, it’s generally reserved for languages that use a specific symbol type.

  • Date − This datatype is used to store the current date or time in UNIX time format. You can specify your own date time by creating object of Date and passing day, month, year into it.

  • Object ID − This datatype is used to store the document’s ID.

  • Binary data − This datatype is used to store binary data.

  • Code − This datatype is used to store JavaScript code into the document.

  • Regular expression − This datatype is used to store regular expression.


Setup

Before diving into MongoDB, you need to first install MongoDB on your computer. To do this, visit the official mongo website or using brew and download the version for according to specific OS. Here, I’ve used Mac.

brew tap mongodb/brew
brew install mongodb-community@4.4

There are interesting couple of executable binary files.

  • mongod server — Mongo Daemon or mongod is a background process used by MongoDB. It manages all the MongoDB server tasks.

  • mongo shell — It is a command line shell that helps in interacting with the client

  • mongos sharded cluster query router


Now let’s see how we can get this server up and running. To do that on Windows, first you need to create a couple of directories in your C drive. Open up your command prompt inside your C drive and do the following:

mkdir data
cd data
mkdir db

The purpose of /data/db is MongoDB requires a folder to store all data. It is the default data directory path on the drive. Therefore, it is necessary that we provide those directories.


If you start the MongoDB server without those directories, you’ll probably see the error.

After creating the directory, run the following command:

mongod

Now your MongoDB server is up and running!


In order to work with this server, we need a mediator which can act as a client. So open another terminal window and run the following command:

mongo

After running this command, navigate to the window in which you ran the mongod command. You’ll see a ‘connection accepted’ message at the end. That means our installation and configuration is successful!


Just simply run in the mongo shell:

db


Initially, you have a default db called test.


Commands


1. Finding the current database you’re in

db


This command will show the current database you are in. test is the initial database that comes by default.


2. Listing databases

show databases



I currently have five databases. They are: blogDB, postsDB, admin, config and local.


3. Go to a particular database

use <your_db_name>
eg: use blogDB



Here, I’ve moved to the blogDB database.


4. Creating a Database

In relational databases we have concepts of databases, tables, rows and columns. But in NoSQL databases, data is stored in BSON format which is a binary version of JSON. They are stored in collections.


In SQL databases, these are similar to Tables.



SQL terms and NoSQL terms by Victoria Malaya

For creating a database in the mongo shell, use the following command:

use <new_db_name>

If the database with <new_db_name> is present already, the above command will navigate into the existing database. But if the database is not present, then it is going to create the new database and will navigate into it.

After creating a new database, running the show database command will not show your new database until it has any data.


5. Deleting a database

Following command is used to drop an existing database.

db.dropDatabase()


6. Creating a Collection

You can switch to your newly created database with the use command. One way to create collection is to insert data into the collection:

db.testCollection.insert({"name": "dove", "age" : 26, "email": "test@gmail.com"})


This is going to first create your collection testCollection if the collection does not exist. Then it will insert a document with name, age and email.

Other way to create collection is shown below:

db.createCollection("testCollection")

In this way, you’re going to create a collection without inserting data.


7. Inserting Data

We can insert data to a new collection, or to a collection that has been created before. There are three methods of inserting data.

  1. insertOne() is used to insert a single document only.

  2. insertMany() is used to insert more than one document.

  3. insert() is used to insert documents as many as you want.

Below are some examples:

  • insertOne()

db.testCollection.insertOne(
      {
       "name": "bhim", 
       "age": 22,
       "email": "tewst@gmail.com"
      }
)
  • insertMany()

db.testCollection.insertMany([
      {
        "name": "navindu", 
        "age": 22,
        "email": "nav@gmail.com"
      },      {
        "name": "kovid", 
        "age": 27,
        "email": "kovig@gmail.com"
      },
      {
        "name": "john doe", 
        "age": 25,
        "city": "Hyderabad"
      }
   ]
)


The insert() method is similar to the insertMany() method.

Also, notice we have inserted a new property called city on the document for john doe. So if you use find, then you’ll see only for john doe the city property is attached.

This can be an advantage when it comes to NoSQL databases such as MongoDB. It allows for scalability.


8. Lookup data in Collection

Here’s how you can query all data from a collection:

db.testCollection.find()



If you want to see this data in a cleaner, way just add .pretty() to the end of it. This will display document in pretty-printed JSON format.

db.testCollection.find().pretty()


In the above documents, there is an extra field named_id in every document. Whenever you insert a document, MongoDB automatically adds an _id field which uniquely identifies each document.

If you want to display some specific document, you could specify a single detail of the document which you want to be displayed.

db.testCollection.find(
        {
          name: "john doe"
        }
)


If you want only to display people whose age is less than 25, you can use $lt to filter out the documents according to the condition.

db.testCollection.find(         
       {
           age : {$lt : 25}         
       })


Similarly, $gt stands for greater than, $lte is “less than or equal to”, $gte is “greater than or equal to” and $ne is “not equal”.


9. Updating documents

Let’s say you want to update someone’s address or age, how you could do it? Well, see the next example:

db.testCollection.update({age : 22}, {$set: {age: 24}})


The first argument is the field of which document you want to update. If you need to remove a property from a single document, you could do something like this (let’s say you want age to be gone):

db.testCollection.update({name: "navindu"}, {$unset: {age:""}});


10. Removing a document

When you update or delete a document, you just need to specify the _id not just name, age, email or city .

db.testCollection.remove({name: "navindu"});


11. Removing a collection

db.testCollection.remove({});

The above command is not equal to the drop() method which is used to remove all the documents inside a collection, but the remove() method is used to delete all the documents along with the collection itself.


12. Dropping a collection

db.testCollection.drop()


13. Limit method

To limit the records in MongoDB, you need to use limit() method. The method accepts one number type argument, which is the number of documents that you want to be displayed.

db.testCollection.find().limit(2)


14. Sort Method

To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

db.testCollection.find().sort({name: 1})



Indexing


Indexes support the efficient resolution of queries. Without indexes, MongoDB must scan every document of a collection to select those documents that match the query statement. This scan is highly inefficient and require MongoDB to process a large volume of data.


Indexes are special data structures, that store a small portion of the data set in an easy-to-traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field as specified in the index.


1. The createIndex() Method

To create an index, you need to use createIndex() method of MongoDB. The basic syntax of createIndex() method is as follows().

db.testCollection.createIndex({"name":1})


Here key is the name of the field on which you want to create index and 1 is for ascending order. To create index in descending order you need to use -1.


2. The dropIndex() method

You can drop a particular index using the dropIndex() method of MongoDB. The basic syntax of DropIndex() method is as follows().

db.testCollection.dropIndex({"name":1})

Here key is the name of the file on which you want to create index and 1 is for ascending order. To create index in descending order you need to use -1.



3. The dropIndexes() method

This method deletes multiple (specified) indexes on a collection. The basic syntax of DropIndexes() method is as follows() −

db.testCollection.dropIndexes()


4. The getIndexes() method

This method returns the description of all the indexes int the collection. Following is the basic syntax of the getIndexes() method −

db.testCollection.getIndexes()


Logical Operators


MongoDB provides logical operators. The picture below summarizes the different types of logical operators.

reference: MongoDB manual


Let’s say you want to display people whose age is less than 25, and also whose location is Colombo. What we could do?

We can use the $and operator!

db.testCollection.find({$and:[{age : {$lt : 25}}, {city: "colombo"}]});


Advantages of MongoDB over RDBMS

(Reference: TutorialsPoint)

  • Schema less − MongoDB is a document database in which one collection holds different documents. Number of fields, content and size of the document can differ from one document to another.

  • Structure of a single object is clear.

  • No complex joins.

  • Deep query-ability. MongoDB supports dynamic queries on documents using a document-based query language that’s nearly as powerful as SQL.

  • Tuning.

  • Ease of scale-out − MongoDB is easy to scale.

  • Conversion/mapping of application objects to database objects not needed.

  • Uses internal memory for storing the (windowed) working set, enabling faster access of data.



Source: Medium


The Tech Platform

0 comments
bottom of page