0% found this document useful (0 votes)
20 views7 pages

lec_7_part_2

The document provides a tutorial on using Node.js with MongoDB, including steps to create a project, connect to a MongoDB database, create databases and collections, and insert documents. It includes code examples for listing databases, creating a new database and collection, and inserting single and multiple documents. The document emphasizes the use of the MongoDB driver for Node.js and provides connection strings and sample outputs for each operation.

Uploaded by

r.soliman3526
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views7 pages

lec_7_part_2

The document provides a tutorial on using Node.js with MongoDB, including steps to create a project, connect to a MongoDB database, create databases and collections, and insert documents. It includes code examples for listing databases, creating a new database and collection, and inserting single and multiple documents. The document emphasizes the use of the MongoDB driver for Node.js and provides connection strings and sample outputs for each operation.

Uploaded by

r.soliman3526
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

1

Lec 7 part 2: Nodejs & MonogoDB


Create Project
Create a new folder for your project Initialize a new Node.js application in a new
folder:
npm init -y

mongodb driver
install the mongodb driver module from the NPM repository, so that a Node.js
application could interact with MongoDB:
npm install mongodb

Node.js - MongoDB Create Database


Connection strings
The mongodb driver for Node.js is imported into the code with the require()
function. The object of MongoClient class represents a database connection. You
need to pass a connection string to its constructor.
The default connection string is :
mongodb://localhost:27017/
2

Example: List of databases


const {MongoClient} = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017/";
const client = new MongoClient(uri);
try {
// Connect to the MongoDB cluster
await client.connect();
// Make the appropriate DB calls
await listDatabases(client);
} catch (e) {
console.error(e);
} finally {
// Close the connection to the MongoDB cluster
await client.close();
}
}
main().catch(console.error);

async function listDatabases(client) {


databasesList = await client.db().admin().listDatabases();
console.log("Databases:");
databasesList.databases.forEach(db => console.log(` - ${db.name}`));
};
output Databases:
- EdurekaCoursesDB
- admin
- config
- local
- mydatabase
3

Create a new database


Example
const {MongoClient} = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017/mydb";
const client = new MongoClient(uri);
try {
// Connect to the MongoDB cluster
await client.connect();
await createdb(client, "mydatabase");
} finally {
// Close the connection to the MongoDB cluster
await client.close();
}
}
main().catch(console.error);

async function createdb(client, dbname) {


const dbobj = await client.db(dbname);
console.log("Database created");
console.log(dbobj);
}

 Output:
Database created
MongoDatabase { s: { client: [MongoClient], options: [Object], dbName:
'mydatabase' } }
4

Node.js - MongoDB Create Collection


Example
const {MongoClient} = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017/";
const client = new MongoClient(uri);
try {
// Connect to the MongoDB cluster
await client.connect();
await newcollection(client, "mydatabase");
} finally {
// Close the connection to the MongoDB cluster
await client.close();
}
}
main().catch(console.error);

async function newcollection(client, dbname) {


const dbobj = await client.db(dbname);
const collection = await
dbobj.createCollection("products");
console.log("Collection created");
console.log(collection);
}

 Output:
Collection created
Collection { s: { db: [MongoDatabase], options: [Object], name: 'products' } }
5

InsertOne() method
Example
const {MongoClient} = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
try {
// Connect to the MongoDB cluster
await client.connect();
// Make the appropriate DB calls
// Create a single new document
await createdoc(client, "mydatabase",
"products", {
"ProductID": 1,
"Name": "Laptop",
"Price": 25000
});
} finally {
// Close the connection to the MongoDB cluster
await client.close();
}
}
main().catch(console.error);

async function createdoc(client, dbname,


colname, doc) {
const dbobj = await client.db(dbname);
const col = dbobj.collection(colname);
const result = await col.insertOne(doc);
console.log(`New document created with the
following id: ${result.insertedId}`);}
 Output:
New document created with the following id: <ObjectId>
6

insertMany()
Example
const {MongoClient} = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
//const uri = "mongodb+srv://user:[email protected] db.net / ?
retryWrites = true & w = majority ";
const client = new MongoClient(uri);
try {
// Connect to the MongoDB cluster
await client.connect();
// Make the appropriate DB calls
// insert documents
await createdocs(client, [{
'ProductID': 1,
'Name': 'Laptop',
'price': 25000
},
{
'ProductID': 2,
'Name': 'TV',
'price': 40000
},
{
'ProductID': 3,
'Name': 'Router',
'price': 2000
},
{
'ProductID': 4,
'Name': 'Scanner',
'price': 5000
},
{
7

'ProductID': 5,
'Name': 'Printer',
'price': 9000
}
]);
} finally {
// Close the connection to the MongoDB cluster
await client.close();
}
}
main().catch(console.error);

async function createdocs(client, docs) {


const result = await
client.db("mydatabase").collection("products").i
nsertMany(docs);
console.log(`${result.insertedCount} new document(s) created with the
following id(s):`);
console.log(result.insertedIds);
}

 Output:
5 new document(s) created with the following id(s):
{
'0': <ObjectId>,
'1': <ObjectId>,
'2': <ObjectId>,
'3': <ObjectId>,
'4': <ObjectId>
}

You might also like