EXPERIMENT NO: 9 DATE: / /
TITLE: MongoDB with NodeJs
OBJECTIVES: On completion of this experiment students will be able to…
➢ know the concept of Connectivity of MongoDB with Nodejs
THEORY:
Install MongoDB :
You can download a free MongoDB database at https://www.mongodb.com.
Or get started right away with a MongoDB cloud service at
https://www.mongodb.com/cloud/atlas.
Let us try to access a MongoDB database with Node.js.
To download and install the official MongoDB driver, open the Command Terminal and
execute the following:
Download and install mongodb package:
C:\Users\Your Name>npm install mongodb
Note: First open another terminal an run command mongod to start your mongoDB
Node.js MongoDB Create Database
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
C:\Users>node demo_create_mongo_db.js
Node.js MongoDB Create Collection:
A collection in MongoDB is the same as a table in MySQL
Creating a Collection
To create a collection in MongoDB, use the createCollection() method:
Example
Create a collection called "customers":
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.createCollection("customers", function(err, res) {
if (err) throw err;
console.log("Collection created!");
db.close();
});
});
Page 2 of 3
EXERCISE:
1.Create Node.js Application to Connect Node JS with MongoDB
EVALUATION:
Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)
Signature with date: ________________
Page 3 of 3