Display MongoDB data in HTML

In this MongoDB tutorial, we are going to discuss “display MongoDB data in HTML”. Additionally, we will also discuss the following topics:

  • Display MongoDB data in HTML
  • How to display MongoDB data on the HTML page
  • Display MongoDB data in HTML insert
  • Display MongoDB data in HTML using python

Display MongoDB data in HTML

In this topic, you will learn the display MongoDB data in HTML. Let’s understand the theory behind displaying MongoDB data in HTML

Between the HTML presenting your data and your MongoDB storing your data, there are some missing pieces. I’ve listed them in order, from the front end to the back end.

  1. Client Side web application.
  2. Application programming interface (API).
  3. Server Side Application.
  4. Object Relational Model (ORM).

Your Javascript is run by your HTML page as a Client-Side Application. This JS code should make a call to the Application Programming Interface (API) to get the data it needs. Then, it should take that data and present it on the HTML.

Application Programming Interface. API calls are typically done using AJAX. You will use jQuery AJAX to make an API call. Google how to make API calls. You can make a GET or a POST request (among many other methods).

Server-Side Applications typically is written with Java. But spinning up a server with NodeJS is also pretty easy. Your server-side application will have routes. Each route will speak to a controller, which in turn makes the proper database call using the ORM.

Update: Even python can be used to run server-side applications.

Object Relational Model is basically a plugin that lets your server-side application talk to the database. This is very useful when the database and your server talk in two different languages. Since you are using Mongo and our hypothetical server-side application is in Javascript (if you are using Node and not Python or Java), the ORM doesn’t do that much work. Monk is a lightweight ORM typically used for NodeJS.

How to display MongoDB data on the HTML page

We will fetch that data using Node js and display it in HTML (ejs). The EJS is a template system. In EJS syntax, you define HTML pages and indicate where various data will appear on the page. Then, your app combines data with the template and “renders” a complete HTML page where EJS takes your data and inserts it into the web page according to how you’ve defined the template.

You have to follow the below steps to display MongoDB data on the HTML page:

  1. Create Node Express js App
  2. Install express flash ejs body-parser mongoose dependencies
  3. Connect App to MongoDB
  4. Create Model
  5. Create Routes
  6. Create HTML Table and Display List
  7. Import Modules in App.js
  8. Start App Server

You can easily display MongoDB data on the HTML page by following the above steps.

Also, read: MongoDB find last inserted document

Display MongoDB data in HTML insert

We will use Node.js for the HTML concept in MongoDB for inserting the document. And, the insertOne() method to used to insert a record or document into a collection.

Note that, we can also insert multiple documents by using the insertMany() method.

Example:

If you are new to node.js then you have to download the latest version of Node.js and install the MongoDB Node.js driver allows so you can easily interact with MongoDB databases from within Node.js applications. Use the below query to install the MongoDB Node.js driver:

# MongoDB Node.js Driver install
npm install mongodb

In this example, we will use the node.js for HTML and insert a document in the customers’ collection.

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("corporation");
  var myobj = { name: "Company Inc", address: "Highway 37, USA" };
  dbo.collection("customers").insertOne(myobj, function(err, res) {
    if (err) throw err;
    console.log("1 document inserted");
    db.close();
  });
});

In the code, first, we have to make the connection with the MongoDB server.

  • After that, we have define the MongoDB URL “mongodb://localhost:27017/”
  • Cover the functions that interact with the database with a try/catch statement so that it can handle any unexpected errors.
  • Create a new database with the name corporation.
  • Enter a document field, insert it into the customers’ collection.
  • Insert one document by using the insertOne() method.
  • After that, we have used the console.log() function of JavaScript which is used to print any kind of variables defined before in it or to just print any message.

See the execution of the code:

 node e:\Practice\customers.js

Here, we have to write “node” to execute or test the javascript code and define the executable file location or path.

Display MongoDB data in HTML insert
Display MongoDB data in HTML insert

We have successfully inserted the document into the customers’ collection.

Read: How to change collection name in MongoDB

Display MongoDB data in HTML using python

In this topic, you will learn to find the MongoDB data in HTML using python.

Follow the below Steps to fetch data from the MongoDB database:

The following code where import the pymongo in use to connect the python file to the database. After importing, create an instance of MongoClient and build a connection to the default host, i.e., localhost and port 27017.

import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")

Suppose we have a collection name “person” that contains name, age, and gender. And we want to The following want to display the person collection whole information on a webpage in HTML.

{ "_id" : ObjectId("6167b25df7f983cb6c551239"), "name" : "James", "age" : 25, "gender" : "male" }
{ "_id" : ObjectId("6167b25df7f983cb6c55123a"), "name" : "John", "age" : 28, "gender" : "male" }
{ "_id" : ObjectId("6167b25df7f983cb6c55123b"), "name" : "Mary", "age" : 33, "gender" : "female" }
{ "_id" : ObjectId("6167b25df7f983cb6c55123c"), "name" : "David", "age" : 22, "gender" : "male" }
{ "_id" : ObjectId("6167b25df7f983cb6c55123d"), "name" : "Jessica", "age" : 27, "gender" : "female" }
{ "_id" : ObjectId("6167b25df7f983cb6c55123e"), "name" : "Daniel", "age" : 27, "gender" : "male" }

Here, we have obtained the collection of “person” data. MongoDB provides the find() method to return the document or documents based on the specified criteria.

import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = client["myDB"]
mycol = mydb["person"]

stud = []

tbl = "<tr><td>Name</td><td>Age</td><td>gender</td></tr>"
stud.append(tbl)

for y in mycol.find():
    a = "<tr><td>%s</td>"%y['name']
    stud.append(a)
    b = "<td>%s</td>"%y['age']
    stud.append(b)
    c = "<td>%s</td></tr>"%y['gender']
    stud.append(c)

Create the HTML Template

After that, we have created an HTML template and stored it in a contents variable. In this template, we have passed the above list variable student within the HTML table element.

contents = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
<title>Python Webbrowser</title>
</head>
<body>
<table>
%s
</table>
</body>
</html>
'''%(student)

Web Browser Module

The webbrowser module is available with the Python package. And, It gives a feature to open a webpage in the browser.

In the below code, we have created an HTML file and placed the above-generated HTML content, and rendered it in a web browser.

filename = 'info.html'

def main(contents, filename):
    output = open(filename,"w")
    output.write(contents)
    output.close()

main(contents, filename)    
webbrowser.open(filename)

Complete code

At the start of this topic, we have divided the complete code into parts to explain the step-by-step process to display data from MongoDB to HTML. Here, we join that all to get the complete code:

import pymongo
import webbrowser

client = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = client["myDB"]
mycol = mydb["person"]

student = []

tbl = "<tr><td>Name</td><td>Age</td><td>gender</td></tr>"
student.append(tbl)

for y in mycol.find():
    a = "<tr><td>%s</td>"%y['name']
    student.append(a)
    b = "<td>%s</td>"%y['age']
    student.append(b)
    c = "<td>%s</td></tr>"%y['gender']
    student.append(c)

contents = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
<title>Python Webbrowser</title>
</head>
<body>
<table>
%s
</table>
</body>
</html>
'''%(student)

filename = 'info.html'

def main(contents, filename):
    output = open(filename,"w")
    output.write(contents)
    output.close()

main(contents, filename)    
webbrowser.open(filename)

The above code returns the following output to the browser –

Display MongoDB data in HTML using python
Display MongoDB data in HTML using python

We have successfully retrieved the documents in HTML using python.

You may also like to read the following MongoDB articles.

So, in this tutorial, we have understood How to display MongoDB data on the HTML page. Additionally, we have also discussed the following topics:

  • Display MongoDB data in HTML
  • How to display MongoDB data on the HTML page
  • Display MongoDB data in HTML insert
  • Display MongoDB data in HTML using python