MongoDB & SQL

Soufiane Oucherrou
2 min readMay 11, 2020

What is MongoDB?

MongoDB is a document-based NoSQL database that is scalable and flexible.

Document-based

MongoDB stores data using a document data structure. Documents are JSON-like objects with key-value pairs.

Let’s take a look at an example of a user document

{
_id: ObjectId("5d8d5b50a5b9d4a3c402f571"),
email: "soufiane@gmail.com",
password_digest: "Ke&63h1z$mK9jd37nhdnsuoisnwe",
age: 27,
address: {
city: "NYC",
street: "here",
zipcode: 1
},
posts: [
ObjectId("4a1h3m42a5b9d4i9dc405l742"),
ObjectId("b9x2m45a5b7h7e3ml403a0bg"),
]
}

You may have noticed the several different datatypes being stored in the document above. This is one of the benefits of using this document data-structure. We are able to store not only arrays, but sub-documents as well. The sub-document in this example is the value of the address key.

Embedding

Storing sub-documents within a document is know as embedding. Embedding related information provides better read performance, also because the ability to retrieve related data with one database query. Additionally, embedded data models make it possible to update related data during a single operation.

You should use an embedded data model when you are trying to model the following:

  • One-to-One relationships
  • Small One-to-Many relationships

You may have also noticed in the example user document, there are several ObjectIds stored within the posts array. These ObjectIds hold a reference to a document in a separate collection. This pattern is known as referencing.

Referencing will seem very familiar after working with an electronic database. However, the advantages of embedding are lost once we use referencing. Despite this, here are a couple of situations where we’d got to use referencing:

  • Many-to-Many relationships
  • Modeling large hierarchical data sets
  • Large One-to-Many relationships

Flexible

MongoDB’s flexibility comes from utilization dynamic schemas also because the document arrangement .

A dynamic schema allows you to start out with a basic schema which will be updated easily. This has been important to more modern apps and corporations , because it aids their teams in building a base app quickly and adapting it as required .

Recall that the document arrangement is JSON-like. it’s ready to store a spread of various data types, but more importantly, it are often directly interfaced within our backend code. You not got to use an ORM (e.g. Active Record) to map data from a database to an object that you simply can easily interface with. This accelerates the event process as you’ve got one less thing to stress about.

--

--