Home » MongoDB » Mapping relational database to MongoDB

Mapping relational database to MongoDB

If you are coming from an RDBMS/SQL background, understanding NoSQL and MongoDB concepts can be bit difficult while starting because both the technologies have very different manner of data representation.By mapping, means if we have a concept in RDBMS/SQL, we will see what its equivalent concept in MongoDB.

We will start with mapping the basic relational concepts like table, row, column, etc and move to discuss indexing and joins. We will then look over the SQL queries and discuss their corresponding MongoDB database queries. The article assumes that you are aware of the basic relational database concepts and SQL.

In this tutorial, we will discuss the mapping between relational database and MongoDB.

Mapping Tables, Columns, and Rows

MongoDb Installation


  • Collection in MongoDB is equivalent to the tables in RDBMS.
  • Document in MongoDB is equivalent to the rows in RDBMS.
  • Field in MongoDB is equivalent to the columns in RDBMS.

Following is an example of a document having some fields storing details of a user:

{
"_id": ObjectId("5146bb52d8524270060001f3"),
"name":"Mukesh",
"age": 30,
"city": "Bangalore",
"email": "mark@g.com",
"user_name": "mraj"
}

Fields (key and value pairs) are stored in document, documents are stored in collection and collections are stored in database.

This is how a document looks in MongoDB: As you can see this is similar to the row in RDBMS. The only difference is that they are in JSON format.

MongoDb Installation


Table vs Collection

To understand the mappings better, let us take an example of an SQL table users and its corresponding structure in MongoDB. As shown below, each row in the SQL table transforms to a document and each column to a field in MongoDB.

MongoDb Installation


Dynamic Schema

Another cool thing about MongoDB is that it supports dynamic schema which means one document of a collection can have 4 fields while the other document has only 3 fields. This is not possible in relational database.

Let see on this example which is about two data representation on document in the one collection.

MongoDb Installation


From the above picture we can look that the first document has CITY,STATE and LAT_N field which is not in the second document.Similarly in third document LONG_W is not found.

This model of dynamic schema is the reason why NosSQL databases are highly scalable in terms of design. Various complex schemas (hierarchical, tree-structured, etc) which would require number of RDBMS tables can be designed efficiently using such documents.


Previous Next Article
comments powered by Disqus