A Comprehensive Guide on How to Create Views in MongoDB

MongoDB, an open-source, document-oriented database, has been at the forefront of flexible and scalable data solutions. The NoSQL structure of MongoDB allows it to store substantial amounts of semi-structured data, making it a top choice for big data and real-time web applications. I have talked about how to create relations in MongoDB in this blog post. But have you ever wondered how to create views in MongoDB to streamline your data retrieval and enhance security? Let’s delve into the specifics.

The ability to create views is a standout feature of MongoDB that many developers overlook. In essence, a view is a saved query, providing a virtual subset of data from existing collections without requiring separate data storage. But how does one go about creating views in MongoDB? Let’s explore this further.

Use cases

The use cases for views are numerous, highlighting their potential in data management. A prime reason to create views in MongoDB is to limit data exposure. For instance, if you have a collection with user data, you wouldn’t want every field to be accessible to all users. Creating a view with only the necessary fields provides a way to effectively manage data visibility. Furthermore, views enable you to present a simplified version of your data schema, fostering user-friendly interaction with your data.

Moreover, views in MongoDB are robust tools for complex data operations. Are you joining data across collections or executing complex aggregations? Creating views in MongoDB can be your savior. By encapsulating the query logic in a view, you can conveniently reuse it, saving you from writing complex queries every time, especially with large datasets.

How to create views in MongoDB

So, how to create views in MongoDB? It’s a relatively straightforward process. You use the “db.createView()” function, specifying the view name, source collection, and an aggregation pipeline. For instance, let’s assume we have a collection named “orders,” and we wish to create a view that only displays the “customerName” and “product” fields. The command would look like this:

db.createView(
    "viewOrders",   // the name of the view
    "orders",       // the name of the source collection
    [
        {
            $project : {   // limit the fields to include in the output
                _id : 0,
                customerName : 1,
                product : 1
            }
        }
    ]
);

With the above command, we successfully create a new view called “viewOrders.” This view will only include the “customerName” and “product” fields from each document in the “orders” collection. Learning how to create views in MongoDB offers flexible, secure, and efficient ways to interact with your data.

Conclusion

Whether you are new to MongoDB or a seasoned pro looking to enhance your skills, understanding how to create views in MongoDB is a powerful tool in your developer’s toolkit. Leverage views to provide secure, simplified, and efficient data access, giving your MongoDB usage a substantial boost.

How to create relations in MongoDB

I have mentioned MongoDB in some of my previous blog posts. And, from those posts, you may know that one of the differences between MongoDB (or NoSQL databases, in general) and traditional relational (or SQL) databases, is that MongoDB is non-relational. In other words, relations between entities in the database are not enforced in MongoDB. However, relational databases (like MySQL or PostgreSQL) can enforce relations between tables. But, as you will see in this blog post, it is possible to implement relations in MongoDB. So, how to create relations in MongoDB?

Different approaches

MongoDB provides a lot of flexibility when it comes to the structure of the data that’s stored in it. As a result of this flexibility, there is more than one approach you can take to implement relations in MongoDB. I will list two approaches in this post. With each of these approaches, I will talk about the advantages and disadvantages. Also, I’ll touch base on when it makes more sense to use one over the other.

Before I get into the different approaches, let us quickly review how data is stored in MongoDB. A table, or entity, in MongoDB is called a collection. Each collection has a set of documents stored in it. Each document is stored in a special JSON format. The below is an example of how an employee document may look like.

{
     "_id": ObjectId("5bf41179997910230e41153e"),
     "firstName": "John",
     "lastName": "Doe",
     "active": true,
     "dateCreated": "2020-11-26"
 }

As you can see from the above, documents look like JavaScript objects, where each field is a set of key-value pair.

Embedding

The first approach to creating a relation in MongoDB is to embed a document inside another. Keeping the same employee document as an example, if we wanted to add department information to it, we could embed a department document inside the employee document. The result would look like this:

{
     "_id": ObjectId("5bf41179997910230e41153e"),
     "firstName": "John",
     "lastName": "Doe",
     "active": true,
     "dateCreated": "2020-11-26",
     "department" : {
          "departmentName": "IT",
          "departmentManager": "Jane Smith",
          "departmentLocation": "6th Floor"
     }
 }

Adding a relation between the employee entity and the department entity may look like this. The department document is embedded inside the employee entity.

Advantages

The biggest advantage that you get when implementing this approach, is that it is very easy to implement. If you wanted to retrieve an employee record, and get information about their department, you could do this with a very simple query. Simply retrieving the record itself gives you all you need about the department as well. There’s no need to join or lookup data from any other entity.

Disadvantages

A quick glance at the example above, and it’s evident what the biggest disadvantage is. If the manager of the department is changed (or any other field in the departments entity, for that matter), then you will have to update that information in all of the employees documents as well. This will quickly become unmanageable as the number of documents gets larger.

When to use

I would recommend using the embedding approach only if the number of documents is small, and the data does not change often, or at all. Otherwise, updating data in the embedded documents becomes unmanageable.

Referencing

An alternative approach that you can take if you want to implement relations in MongoDB, is to reference a document from another document. This approach is similar to having a foreign key in a relational database. To take the same employee-department example, if we wanted to use references, the employee document would look like this:

{
     "_id": ObjectId("5bf41179997910230e41153e"),
     "firstName": "John",
     "lastName": "Doe",
     "active": true,
     "department": ObjectId("5fd930b2ca2d7a28b214892d"),
     "dateCreated": "2020-11-26"
 }

Using this approach, the department field is a reference to a document in another collection (the departments collection).

Advantages

The biggest advantage to using this approach is that updating anything in the departments collection does not require an update in the employees collection. The changes would be reflected in the employee record, because it is pointing to the department record.

Disadvantage

The only disadvantage here, is that if you wanted to retrieve an employee record, along with information about the department, you would have to perform some kind of a lookup. This lookup operation might cause an overhead that can be expensive, in terms of performance.

When to use

I recommend using this approach for most scenarios. Even though looking up the referenced records is more expensive (performance-wise) than having them embedded, however, in most cases, this cost in performance is negligible compared to the cost of having to update all the embedded records.

Conclusion

Even though MongoDB does not force relations, you can create relations in MongoDB by using one of two approaches. Embedding a document inside another document is one way. It is easy to implement, and does not have the overhead of looking up the related documents when retrieving. I recommend using this approach in simple scenarios where the data does not change often. The other approach is to reference the related documents. With referencing, you can modify one collection without having to modify the related documents. You can justify the overhead in the lookup in cases where you update the data frequently.

If you have any questions, please leave a comment here, or use the contact page.

What is the MEAN Stack?

You may have heard the term MEAN Stack in web development. I will explain where this term comes from, and what are the advantages of creating web applications using the MEAN Stack. MEAN Stack stands for MongoDB, Express.js, Angular and Node.js. Let’s first talk about the different parts that make up a MEAN Stack application, describe why it’s a good idea to create web applications by using it.

MongoDB

MongoDB is a NoSQL database. This is the database of choice for developers building MEAN applications. The data that’s stored in a MongoDB database is in JSON format. This makes it an excellent candidate for the database in this type of applications.

Express.js

Express.js is one of the most popular frameworks, used with Node.js, for creating web applications. It allows developers to easily respond to HTTP user requests.

Angular

Angular was designed by Google to allow developers to create web applications (you can create other types of applications with Angular, but I’ll stick to web applications in this post). Ever since version 2 of Angular (also known as Angular 2), the language that you have to use is TypeScript. This is a Microsoft language that’s designed to improve upon plain JavaScript. So, if you already know JavaScript, then the learning curve for coding in TypeScript is not steep at all.

Node.js

Historically, JavaScript in web applications worked in the browser only. However, Node.js is JavaScript that runs on the server. You can think of it as the server for a MEAN application.

Advantages

As you can see from the above, all of the technologies in a MEAN application use JavaScript as the programming language. This provides a big advantage, in the sense that all the stacks of the application use the same language. It is especially advantageous for small teams, like in startups, where one developer handles all the different parts of the application.

Conclusion

MEAN Stack applications use MongoDB, Express.js, Angular and Node.js for developing web applications. It is a great way for web developers to use the same language across all the parts of the web application. In some cases, developers can replace Angular with Rect. In which case, you would refer to it as the MERN Stack. If you have any questions, feel free to leave a comment here, or use the contact page.

What you need to learn to become a web developer

People often ask me this question, what do I need to learn to become a web developer. There’s no short answer to this question. And, the answer always starts with “it depends…”. In this blog post, I will try to deep dive into the different web technologies that you can learn to become a web developer.

In a previous blog post, I talked about the different types of web developers depending on what part of the web application they work on. To summarize, a web developer can be a front end, back end or full-stack developer. The part of the web application that you want to work on, will ultimately decide the technologies that you need to learn.

However, regardless of what type of web developer you want to be, learning HTML is a must. This is because HTML is the language that the browser interprets in order to display a web page. In most cases, HTML is written by the front end developer. But, it is very important for back end developers to know HTML as well. This is because they often need to send it back to the browser. So, think of HTML as the universal language that all types of web developers need to know.

What you need to learn: Front end

For a front end developer, in addition to HTML, they need to learn these languages/frameworks:

CSS

Cascading Style Sheets is the language used to style web pages. Think of HTML as the language that tells the browser what to display, and CSS tells it how to display it. Using CSS, you can give your pages colour, position the different elements of a web page and more.

JavaScript

JavaScript is a language that runs on the browser, and provides you with some very useful functionality. Let’s say that you have a contact form on your page, and you need to make sure that the user types a valid email address. One way to do this, is to validate the email address on the server once the users clicks the Submit button. However, the better option would be to do the validation on the browser itself. This will save the user the extra time it takes for the server to do the validation and return the result. It gives a better user experience overall.

Angular

Angular is a framework developed by Google, and used to create Single Page Applications (SPA). A SPA application gives the user a very responsive user-experience. Interacting with an application that was developed using Angular, is similar to interacting with a regular desktop application. The user does not experience the lag of the browser sending a request to the server, and waiting for the response. Everything feels more “snappy” and responsive. In a SPA application, the browser does send a request to the server, of course. But it is done in a way that feels more responsive to the user. To develop Angular applications, you have to know HTML, CSS and a language called TypeScript. This is a variant of JavaScript, and aims to improve on some of its shortcomings.

There are more frameworks that allow you to create SPA applications, other than Angular. For example, ReactJS and VueJS. However, I will stick to talking about Angular here because that’s my preferred framework.

What you need to learn: Back end

As a back end developer, there are more options to choose from than a front end developer. One major factor that may dictate what language you have to learn as a back end developer, is the Operating System of the web server where the application will be hosted. This is because not all languages run on all operating systems.

ASP.NET

ASP.NET is a Microsoft technology that can be used to create web applications. You can use different programming languages to create ASP.NET applications, but the most popular one is C# (pronounced C Sharp). ASP.NET runs only on Windows web servers. A more modern version of ASP.NET is ASP.NET Core.

ASP.NET Core

This is the enhanced version of ASP.NET, and is capable of running on Windows as well as Linux web servers. As far as programming languages are concerned, you can write ASP.NET Core applications using C# as well.

Node.js

You can create server side code using Node.js. The code is written in JavaScript and can be run on different types of operating systems. One advantage of using a JavaScript server side technology, is that you can have the same language (JavaScript) running on the server and the client side.

PHP

PHP is one of the oldest and most popular programming languages used for creating web applications. It powers one of the most popular blogging platforms on the Internet, WordPress.

Python

Python has been increasing in popularity in recent years. You can use it to create web applications, using frameworks like Django. One of the advantages of Python is that it usually requires less code to write something in Python than in other programming languages. This is because of the syntax of the language.

Database technologies

As a back end developer, you need to learn a database technology as well. You have to be extremely familiar with the core concepts of databases. Concepts like, tables, fields, primary fields, relations, etc. In addition, you have to know the ins and outs of the language used for querying (retrieving) the data from the database. Some of the most popular databases are:

  • Microsoft SQL Server
  • MySQL
  • PostgreSQL
  • MongoDB

Microsoft SQL Server, MySQL and PostgreSQL are all examples of relational databases. However, MongoDB is one of the most popular type of database technologies called NoSQL. I will not go into all of the differences between SQL and NoSQL databases in this blog post. But, one of the differences, is that in NoSQL databases the data does not have to be structured in a certain way. Meaning, you can start with a database structure, and then change that structure to something else without affecting the existing data.

What you need to learn: Full-stack

As a Full-stack web developer, you have to be able to create the whole application on your own. Which means, you need to learn some technologies from the front end stack, and some from the back end stack.

Courses to learn web development

If you are looking for good resources or courses to learn any of these languages and technologies, then one of the best websites for such courses is Udemy. It has a wide range of courses on these technologies, and more. Also, regardless of your current experience level, there’s a very good change that you’ll find the right course for you.

Conclusion

For any questions on what you need to learn to become a web developer, please feel free to leave a comment here or use our contact page.