0% found this document useful (0 votes)
10 views9 pages

Lec 8

The document provides a comprehensive guide on using Node.js with MongoDB, covering operations such as finding, sorting, deleting, and updating documents. It includes code examples for connecting to a MongoDB database, executing queries, and applying various MongoDB operators. Additionally, it explains how to traverse results and perform operations like filtering by key-value pairs and using logical operators.

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)
10 views9 pages

Lec 8

The document provides a comprehensive guide on using Node.js with MongoDB, covering operations such as finding, sorting, deleting, and updating documents. It includes code examples for connecting to a MongoDB database, executing queries, and applying various MongoDB operators. Additionally, it explains how to traverse results and perform operations like filtering by key-value pairs and using logical operators.

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/ 9

1

Node.js - MongoDB Find


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 listing
await listall(client, "mydatabase", "products");
} finally {
// Close the connection to the MongoDB cluster
await client.close();
}
}
main().catch(console.error);
async function listall(client, dbname, colname) {
const result = await
client.db(dbname).collection(colname).find({}).toArray();
console.log(JSON.stringify(result));
}
Output:
[{"_id":"6747471cf3ed1447c17b24fd","ProductID
":1,"Name":"Laptop","Price":25000},{"_id":"674
74acc43db2b3fe1a0b770","ProductID":1,"Name":
"Laptop","price":25000},{"_id":"67474acc43db2
b3fe1a0b771","ProductID":2,"Name":"TV","price"
:40000},{"_id":"67474acc43db2b3fe1a0b772","P
roductID":3,"Name":"Router","price":2000},{"_i
d":"67474acc43db2b3fe1a0b773","ProductID":4,
"Name":"Scanner","price":5000},{"_id":"67474a
cc43db2b3fe1a0b774","ProductID":5,"Name":"Pri nter","price":9000}]
2

You can also traverse the resultset with a forEach loop:


// display selected attr. values
var count = 0;
result.forEach(row => {
count++;
console.log(count, row['Name'],
row['price']);
});

 Output:
1 Laptop 25000
2 TV 40000
3 Router 2000
4 Scanner 5000
5 Printer 9000

Find By Key and Value


async function listbykeyvalue(client, dbname, colname) {
const result = await
client.db(dbname).collection(colname).find({ "Name": "TV" }).toArray();
console.log(JSON.stringify(result));
}
// search by key value
await listbykeyvalue(client, "mydatabase", "products");

Output:
[{"_id":"67474acc43db2b3fe1a0b771","ProductID":2,"Name":"TV","price":40000]
3

 Key value find:


async function listbykeyvalue(client, dbname, colname, keyValue) {
const result = await
client.db(dbname).collection(colname).find(keyValue).toArray();
console.log(JSON.stringify(result));

}
// search by key value
var keyValue = { Name: "TV" };
await listbykeyvalue(client, "mydatabase", "products", keyValue);

MongoDB Operators
The operators are used in find() method to apply filter
Sr.No MongoDB Operator Description
1 $eq equal to (==)
2 $gt greater than (>)
3 $gte greater than or equal to (>=)
4 $in if equal to any value in array
5 $lt less than (<)
6 $lte less than or equal to (<=)
7 $ne not equal to (!=)
8 $nin if not equal to any value in array
4

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 listing
await fetchdocs(client, "mydatabase", "products");
} finally {
// Close the connection to the MongoDB cluster
await client.close();
}
}
main().catch(console.error);
async function fetchdocs(client, dbname, colname) {
const result = await
client.db(dbname).collection(colname).find({ "price": { $gt: 10000 } }).toArray();
console.log(JSON.stringify(result));
}
Output:
[{"_id":"67474acc43db2b3fe1a0b770","ProductI
D":1,"Name":"Laptop","price":25000},{"_id":"67
474acc43db2b3fe1a0b771","ProductID":2,"Name ":"TV","price":40000}]
5

The $and as well as $or operators are available for compound logical
expressions
db.collection.find($and:[{"key1":"value1"}, {"key2":"value2"}])

Example
async function fetchdocs(client, dbname, colname) {
const result = await client.db(dbname).collection(colname).find({
$and: [{ "price": { $gt: 1000 } }, { "price": { $lt: 10000 } }]
}).toArray();
console.log(JSON.stringify(result));
}

Output
[{"_id":"67474acc43db2b3fe1a0b772","Product
ID":3,"Name":"Router","price":2000},{"_id":
"67474acc43db2b3fe1a0b773","ProductID":4,"N
ame":"Scanner","price":5000},{"_id":"67474a
cc43db2b3fe1a0b774","ProductID":5,"Name":"P rinter","price":9000}]

Node.js - MongoDB Sort


The syntax for ascending order:
result = col.find(query).sort(field:1);
The syntax for descending sort:
result = col.find(query).sort(field:-1);
6

Example (Ascending sort)


const {MongoClient} = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017/";
const client = new MongoClient(uri);
try {
await client.connect();
await sortdocs(client, "mydatabase", "products");
} finally {
await client.close();
}
}
main().catch(console.error);
async function sortdocs(client, dbname, colname) {
var mysort = { price: 1 };
const result = await
client.db(dbname).collection(colname).find({}).sort(mysort).toArray();
result.forEach(element => {
console.log(element);
});
}
7

Output
{
_id: new ObjectId('67474acc43db2b3fe1a0b772'),
ProductID: 3,
Name: 'Router',
price: 2000
}{
_id: new ObjectId('67474acc43db2b3fe1a0b773'),
ProductID: 4,
Name: 'Scanner',
price: 5000
}{
_id: new ObjectId('67474acc43db2b3fe1a0b774'),
ProductID: 5,
Name: 'Printer',
price: 9000
}{
_id: new ObjectId('67474acc43db2b3fe1a0b770'),
ProductID: 1,
Name: 'Laptop',
price: 25000
}{
_id: new ObjectId('67474acc43db2b3fe1a0b771'),
ProductID: 2,
Name: 'TV',
price: 40000
}
8

Node.js - MongoDB Delete

deleteOne()
async function deldocs(client, dbname, colname) {
var myqry = { Name: "TV" };
const result = await client.db(dbname).collection(colname).deleteOne(myqry);
console.log("Document Deleted");
}

deleteMany()
async function deldocs(client, dbname, colname) {
var myqry = {"price": { $gt: 10000 } };
const result = await client.db(dbname).collection(colname).deleteMany(myqry);
console.log("Documents Deleted");
}

Drop Collection

drop()
async function dropcol(client, dbname, colname) {
const result = await client.db(dbname).collection(colname).drop();
console.log("Collection dropped ");
}

dropCollection()
async function dropcol(client, dbname, colname) {
const result = await client.db(dbname).dropCollection(colname);
console.log("Collection dropped");
}
9

Node.js - MongoDB Update

updateOne()
async function updatedocs(client, dbname, colname) {
var qry = { ProductID: 3 };
var vals = { $set: { Name: "Router", price: 2750 } };
const result = await client.db(dbname).collection(colname).updateOne(qry,
vals);
console.log("Document updated");
}

updateMany()
async function updatemanydocs(client, dbname, colname) {
var qry = { Name: /er$/ };
var vals = { $inc: { price: 125 } };
const result = await client.db(dbname).collection(colname).updateMany(qry,
vals);
console.log("Documents updated");
}

You might also like