diff --git a/Week4/homework/ex1-aggregation/index.js b/Week4/homework/ex1-aggregation/index.js new file mode 100644 index 000000000..2a3583bde --- /dev/null +++ b/Week4/homework/ex1-aggregation/index.js @@ -0,0 +1,102 @@ +const { MongoClient, ServerApiVersion } = require("mongodb"); +require("dotenv").config(); + +const uri = process.env.MONGODB_URL; + +// Create a MongoClient with a MongoClientOptions object to set the Stable API version +const client = new MongoClient(uri, { + serverApi: { + version: ServerApiVersion.v1, + strict: true, + deprecationErrors: true, + }, +}); + +async function run() { + try { + // Connect the client to the server (optional starting in v4.7) + await client.connect(); + // Send a ping to confirm a successful connection + await client.db("databaseWeek4").command({ ping: 1 }); + console.log( + "Pinged your deployment. You successfully connected to MongoDB!" + ); + + const mongoClient = client + .db("databaseWeek4") + .collection("population_pyramid_1950-2022"); + + console.log(await getPopulationPerCountry(mongoClient, "Netherlands")); + + console.log(await getContinentInfo(mongoClient, 1990, "100+")); + } finally { + await client.close(); + } +} +run().catch(console.dir); + +const getPopulationPerCountry = async (mongoClient, country) => { + const pipeline = [ + { + $match: { + Country: country, + }, + }, + { + $group: { + _id: "$Year", + countPopulation: { + $sum: { + $add: ["$M", "$F"], + }, + }, + }, + }, + { + $project: { + _id: 0, + Year: "$_id", + countPopulation: 1, + }, + }, + { + $sort: { + Year: 1, + }, + }, + ]; //end pipeline + + return await mongoClient.aggregate(pipeline).toArray(); +}; + +const getContinentInfo = async (mongoClient, year, age) => { + const pipeline = [ + { + $match: { + Country: { + $in: [ + "AFRICA", + "ASIA", + "EUROPE", + "LATIN AMERICA AND THE CARIBBEAN", + "NORTHERN AMERICA", + "OCEANIA", + ], + }, + Year: year, + Age: age, + }, + }, + { + $addFields: { + TotalPopulation: { + $sum: { + $add: ["$M", "$F"], + }, + }, + }, + }, + ]; //end pipeline + + return await mongoClient.aggregate(pipeline).toArray(); +}; diff --git a/Week4/homework/ex1-aggregation/package-lock.json b/Week4/homework/ex1-aggregation/package-lock.json new file mode 100644 index 000000000..6ca37528e --- /dev/null +++ b/Week4/homework/ex1-aggregation/package-lock.json @@ -0,0 +1,179 @@ +{ + "name": "ex1-aggregation", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "ex1-aggregation", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "dotenv": "^17.2.3", + "mongodb": "^7.0.0" + } + }, + "node_modules/@mongodb-js/saslprep": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.4.0.tgz", + "integrity": "sha512-ZHzx7Z3rdlWL1mECydvpryWN/ETXJiCxdgQKTAH+djzIPe77HdnSizKBDi1TVDXZjXyOj2IqEG/vPw71ULF06w==", + "license": "MIT", + "dependencies": { + "sparse-bitfield": "^3.0.3" + } + }, + "node_modules/@types/webidl-conversions": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz", + "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==", + "license": "MIT" + }, + "node_modules/@types/whatwg-url": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-13.0.0.tgz", + "integrity": "sha512-N8WXpbE6Wgri7KUSvrmQcqrMllKZ9uxkYWMt+mCSGwNc0Hsw9VQTW7ApqI4XNrx6/SaM2QQJCzMPDEXE058s+Q==", + "license": "MIT", + "dependencies": { + "@types/webidl-conversions": "*" + } + }, + "node_modules/bson": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/bson/-/bson-7.0.0.tgz", + "integrity": "sha512-Kwc6Wh4lQ5OmkqqKhYGKIuELXl+EPYSCObVE6bWsp1T/cGkOCBN0I8wF/T44BiuhHyNi1mmKVPXk60d41xZ7kw==", + "license": "Apache-2.0", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/dotenv": { + "version": "17.2.3", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.2.3.tgz", + "integrity": "sha512-JVUnt+DUIzu87TABbhPmNfVdBDt18BLOWjMUFJMSi/Qqg7NTYtabbvSNJGOJ7afbRuv9D/lngizHtP7QyLQ+9w==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", + "license": "MIT" + }, + "node_modules/mongodb": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-7.0.0.tgz", + "integrity": "sha512-vG/A5cQrvGGvZm2mTnCSz1LUcbOPl83hfB6bxULKQ8oFZauyox/2xbZOoGNl+64m8VBrETkdGCDBdOsCr3F3jg==", + "license": "Apache-2.0", + "dependencies": { + "@mongodb-js/saslprep": "^1.3.0", + "bson": "^7.0.0", + "mongodb-connection-string-url": "^7.0.0" + }, + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@aws-sdk/credential-providers": "^3.806.0", + "@mongodb-js/zstd": "^7.0.0", + "gcp-metadata": "^7.0.1", + "kerberos": "^7.0.0", + "mongodb-client-encryption": ">=7.0.0 <7.1.0", + "snappy": "^7.3.2", + "socks": "^2.8.6" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-providers": { + "optional": true + }, + "@mongodb-js/zstd": { + "optional": true + }, + "gcp-metadata": { + "optional": true + }, + "kerberos": { + "optional": true + }, + "mongodb-client-encryption": { + "optional": true + }, + "snappy": { + "optional": true + }, + "socks": { + "optional": true + } + } + }, + "node_modules/mongodb-connection-string-url": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-7.0.0.tgz", + "integrity": "sha512-irhhjRVLE20hbkRl4zpAYLnDMM+zIZnp0IDB9akAFFUZp/3XdOfwwddc7y6cNvF2WCEtfTYRwYbIfYa2kVY0og==", + "license": "Apache-2.0", + "dependencies": { + "@types/whatwg-url": "^13.0.0", + "whatwg-url": "^14.1.0" + }, + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==", + "license": "MIT", + "dependencies": { + "memory-pager": "^1.0.2" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + } + } +} diff --git a/Week4/homework/ex1-aggregation/package.json b/Week4/homework/ex1-aggregation/package.json new file mode 100644 index 000000000..0b642de75 --- /dev/null +++ b/Week4/homework/ex1-aggregation/package.json @@ -0,0 +1,16 @@ +{ + "name": "ex1-aggregation", + "version": "1.0.0", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "description": "", + "dependencies": { + "dotenv": "^17.2.3", + "mongodb": "^7.0.0" + } +} diff --git a/Week4/homework/ex2-transactions/index.js b/Week4/homework/ex2-transactions/index.js new file mode 100644 index 000000000..8822a3179 --- /dev/null +++ b/Week4/homework/ex2-transactions/index.js @@ -0,0 +1,9 @@ +import { setup } from "./setup.js"; +import { transfer } from "./transfer.js"; + +async function main() { + await setup(); + await transfer(101, 102, 1000, "Transfer 1000 from 101 to 102"); +} + +main().catch(console.error); diff --git a/Week4/homework/ex2-transactions/package-lock.json b/Week4/homework/ex2-transactions/package-lock.json new file mode 100644 index 000000000..7b39673f9 --- /dev/null +++ b/Week4/homework/ex2-transactions/package-lock.json @@ -0,0 +1,179 @@ +{ + "name": "ex2-transactions", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "ex2-transactions", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "dotenv": "^17.2.3", + "mongodb": "^7.0.0" + } + }, + "node_modules/@mongodb-js/saslprep": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.4.0.tgz", + "integrity": "sha512-ZHzx7Z3rdlWL1mECydvpryWN/ETXJiCxdgQKTAH+djzIPe77HdnSizKBDi1TVDXZjXyOj2IqEG/vPw71ULF06w==", + "license": "MIT", + "dependencies": { + "sparse-bitfield": "^3.0.3" + } + }, + "node_modules/@types/webidl-conversions": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz", + "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==", + "license": "MIT" + }, + "node_modules/@types/whatwg-url": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-13.0.0.tgz", + "integrity": "sha512-N8WXpbE6Wgri7KUSvrmQcqrMllKZ9uxkYWMt+mCSGwNc0Hsw9VQTW7ApqI4XNrx6/SaM2QQJCzMPDEXE058s+Q==", + "license": "MIT", + "dependencies": { + "@types/webidl-conversions": "*" + } + }, + "node_modules/bson": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/bson/-/bson-7.0.0.tgz", + "integrity": "sha512-Kwc6Wh4lQ5OmkqqKhYGKIuELXl+EPYSCObVE6bWsp1T/cGkOCBN0I8wF/T44BiuhHyNi1mmKVPXk60d41xZ7kw==", + "license": "Apache-2.0", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/dotenv": { + "version": "17.2.3", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.2.3.tgz", + "integrity": "sha512-JVUnt+DUIzu87TABbhPmNfVdBDt18BLOWjMUFJMSi/Qqg7NTYtabbvSNJGOJ7afbRuv9D/lngizHtP7QyLQ+9w==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", + "license": "MIT" + }, + "node_modules/mongodb": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-7.0.0.tgz", + "integrity": "sha512-vG/A5cQrvGGvZm2mTnCSz1LUcbOPl83hfB6bxULKQ8oFZauyox/2xbZOoGNl+64m8VBrETkdGCDBdOsCr3F3jg==", + "license": "Apache-2.0", + "dependencies": { + "@mongodb-js/saslprep": "^1.3.0", + "bson": "^7.0.0", + "mongodb-connection-string-url": "^7.0.0" + }, + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@aws-sdk/credential-providers": "^3.806.0", + "@mongodb-js/zstd": "^7.0.0", + "gcp-metadata": "^7.0.1", + "kerberos": "^7.0.0", + "mongodb-client-encryption": ">=7.0.0 <7.1.0", + "snappy": "^7.3.2", + "socks": "^2.8.6" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-providers": { + "optional": true + }, + "@mongodb-js/zstd": { + "optional": true + }, + "gcp-metadata": { + "optional": true + }, + "kerberos": { + "optional": true + }, + "mongodb-client-encryption": { + "optional": true + }, + "snappy": { + "optional": true + }, + "socks": { + "optional": true + } + } + }, + "node_modules/mongodb-connection-string-url": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-7.0.0.tgz", + "integrity": "sha512-irhhjRVLE20hbkRl4zpAYLnDMM+zIZnp0IDB9akAFFUZp/3XdOfwwddc7y6cNvF2WCEtfTYRwYbIfYa2kVY0og==", + "license": "Apache-2.0", + "dependencies": { + "@types/whatwg-url": "^13.0.0", + "whatwg-url": "^14.1.0" + }, + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==", + "license": "MIT", + "dependencies": { + "memory-pager": "^1.0.2" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + } + } +} diff --git a/Week4/homework/ex2-transactions/package.json b/Week4/homework/ex2-transactions/package.json new file mode 100644 index 000000000..52e40eac9 --- /dev/null +++ b/Week4/homework/ex2-transactions/package.json @@ -0,0 +1,17 @@ +{ + "name": "ex2-transactions", + "version": "1.0.0", + "main": "index.js", + "type": "module", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "description": "", + "dependencies": { + "dotenv": "^17.2.3", + "mongodb": "^7.0.0" + } +} diff --git a/Week4/homework/ex2-transactions/setup.js b/Week4/homework/ex2-transactions/setup.js new file mode 100644 index 000000000..fb55743bc --- /dev/null +++ b/Week4/homework/ex2-transactions/setup.js @@ -0,0 +1,76 @@ +import { MongoClient } from "mongodb"; +import "dotenv/config"; + +const uri = process.env.MONGODB_URL; + +export async function setup() { + const client = new MongoClient(uri); + + try { + await client.connect(); + console.log("Connected to MongoDB!"); + + const db = client.db("databaseWeek4"); + await insertAccountsCollection(db); + } catch (error) { + console.error("Connection error:", error); + } finally { + await client.close(); + } +} + +async function insertAccountsCollection(db) { + const accounts = db.collection("accounts"); + + // clean up + await accounts.drop().catch(() => {}); + + await accounts.insertMany([ + { + account_number: 101, + balance: 2000, + account_changes: [ + { + change_number: 1, + amount: 200, + changed_date: new Date("2025-01-20T10:15:00Z"), + remark: "Deposit", + }, + { + change_number: 2, + amount: -100, + changed_date: new Date("2025-01-23T11:45:00Z"), + remark: "Online Purchase", + }, + ], + }, + { + account_number: 102, + balance: 500, + account_changes: [ + { + change_number: 3, + amount: -50, + changed_date: new Date("2025-01-21T14:30:00Z"), + remark: "ATM Withdrawal", + }, + ], + }, + { + account_number: 103, + balance: 300, + account_changes: [ + { + change_number: 4, + amount: 1000, + changed_date: new Date("2025-01-22T09:00:00Z"), + remark: "Salary Deposit", + }, + ], + }, + { account_number: 104, balance: 50, account_changes: [] }, + { account_number: 105, balance: 0, account_changes: [] }, + ]); + + console.log("Inserted into accounts collection"); +} diff --git a/Week4/homework/ex2-transactions/transfer.js b/Week4/homework/ex2-transactions/transfer.js new file mode 100644 index 000000000..9b8d0ddfe --- /dev/null +++ b/Week4/homework/ex2-transactions/transfer.js @@ -0,0 +1,86 @@ +import { MongoClient } from "mongodb"; +import "dotenv/config"; + +const uri = process.env.MONGODB_URL; + +const client = new MongoClient(uri); + +export async function transfer(from, to, amount, remark) { + const session = client.startSession(); + const db = client.db("databaseWeek4"); + const accounts = db.collection("accounts"); + + const transactionOptions = { + readPreference: "primary", + readConcern: { level: "local" }, + writeConcern: { w: "majority" }, + }; + + try { + await client.connect(); + + const results = await session.withTransaction(async () => { + // get last change_number + const latest = await accounts + .aggregate( + [ + { $unwind: "$account_changes" }, + { + $group: { + _id: null, + maxChange: { $max: "$account_changes.change_number" }, + }, + }, + ], + { session } + ) + .toArray(); + + let next = (latest[0]?.maxChange ?? 0) + 1; + + const senderResult = await accounts.updateOne( + { account_number: from }, + { + $inc: { balance: -amount }, + $push: { + account_changes: { + change_number: next, + amount: -amount, + changed_date: new Date(), + remark, + }, + }, + }, + { session } + ); + + next++; + + const recipientResult = await accounts.updateOne( + { account_number: to }, + { + $inc: { balance: amount }, + $push: { + account_changes: { + change_number: next, + amount, + changed_date: new Date(), + remark, + }, + }, + }, + { session } + ); + + return { senderResult, recipientResult }; + }, transactionOptions); + + console.log("Transaction complete:", results); + } catch (error) { + console.error("Transaction aborted:", error); + await session.abortTransaction(); + } finally { + await session.endSession(); + await client.close(); + } +}