diff --git a/Week4/homework/ex1-aggregation/index.js b/Week4/homework/ex1-aggregation/index.js new file mode 100644 index 000000000..90d67d4bc --- /dev/null +++ b/Week4/homework/ex1-aggregation/index.js @@ -0,0 +1,76 @@ +require("dotenv").config(); +const { MongoClient, ServerApiVersion } = require("mongodb"); + +const DB = "databaseWeek4"; +const COLL = "populations"; + +async function totalPopulationPerYear(client, country) { + const col = client.db(DB).collection(COLL); + const pipeline = [ + { $match: { Country: country } }, + { + $addFields: { + Year: { $toInt: "$Year" }, + M: { $toLong: "$M" }, + F: { $toLong: "$F" }, + }, + }, + { + $group: { + _id: "$Year", + countPopulation: { $sum: { $add: ["$M", "$F"] } }, + }, + }, + { $sort: { _id: 1 } }, + ]; + return col.aggregate(pipeline).toArray(); +} + +async function continentsForYearAge(client, year, age) { + const col = client.db(DB).collection(COLL); + const continents = [ + "AFRICA", + "ASIA", + "EUROPE", + "LATIN AMERICA AND THE CARIBBEAN", + "NORTHERN AMERICA", + "OCEANIA", + ]; + const pipeline = [ + { + $match: { + Country: { $in: continents }, + Year: { $in: [year, String(year)] }, + Age: age, + }, + }, + { + $addFields: { + Year: { $toInt: "$Year" }, + M: { $toLong: "$M" }, + F: { $toLong: "$F" }, + TotalPopulation: { $add: [{ $toLong: "$M" }, { $toLong: "$F" }] }, + }, + }, + // { $sort: { Country: 1 } } // optional + ]; + return col.aggregate(pipeline).toArray(); +} + +async function main() { + const client = new MongoClient(process.env.MONGODB_URL, { + serverApi: ServerApiVersion.v1, + }); + await client.connect(); + try { + const nl = await totalPopulationPerYear(client, "Netherlands"); + console.log(nl); + + const y2020 = await continentsForYearAge(client, 2020, "100+"); + console.log(y2020); + } finally { + await client.close(); + } +} + +main().catch(console.error); diff --git a/Week4/homework/ex2/index.js b/Week4/homework/ex2/index.js new file mode 100644 index 000000000..f6b897542 --- /dev/null +++ b/Week4/homework/ex2/index.js @@ -0,0 +1,48 @@ +// Week4/homework/ex2-transactions/index.js +import "dotenv/config"; +import { MongoClient } from "mongodb"; +import { setup } from "./setup.js"; +import { transfer } from "./transfer.js"; + +const DB = "databaseWeek4"; +const COLL = "accounts"; + +async function showAccounts(label) { + const client = new MongoClient(process.env.MONGODB_URL); + await client.connect(); + try { + const docs = await client + .db(DB) + .collection(COLL) + .find({}, { projection: { _id: 0 } }) + .sort({ account_number: 1 }) + .toArray(); + console.log(`\n=== ${label} ===`); + console.table( + docs.map((d) => ({ + account_number: d.account_number, + balance: d.balance, + last_change: d.account_changes?.[d.account_changes.length - 1], + })) + ); + } finally { + await client.close(); + } +} + +async function main() { + await setup(); + + await showAccounts("Before transfer"); + + await transfer({ + from: 101, + to: 102, + amount: 1000, + remark: "lesson W4 transfer", + }); + + await showAccounts("After transfer"); +} + +main().catch(console.error); diff --git a/Week4/homework/ex2/setup.js b/Week4/homework/ex2/setup.js new file mode 100644 index 000000000..70c38cd02 --- /dev/null +++ b/Week4/homework/ex2/setup.js @@ -0,0 +1,56 @@ +// Week4/homework/ex2-transactions/setup.js +import "dotenv/config"; +import { MongoClient } from "mongodb"; + +const DB = "databaseWeek4"; +const COLL = "accounts"; + +export async function setup() { + const client = new MongoClient(process.env.MONGODB_URL); + await client.connect(); + try { + const db = client.db(DB); + const col = db.collection(COLL); + + await col.drop().catch(() => {}); + await db.createCollection(COLL); + + await col.createIndex({ account_number: 1 }, { unique: true }); + + const now = new Date(); + await col.insertMany([ + { + account_number: 101, + balance: 5000, + account_changes: [ + { + change_number: 1, + amount: 5000, + changed_date: now, + remark: "initial deposit", + }, + ], + }, + { + account_number: 102, + balance: 1000, + account_changes: [ + { + change_number: 1, + amount: 1000, + changed_date: now, + remark: "initial deposit", + }, + ], + }, + ]); + + console.log("setup: accounts seeded"); + } finally { + await client.close(); + } +} + +if (import.meta.url === `file://${process.argv[1]}`) { + setup().catch(console.error); +} diff --git a/Week4/homework/ex2/transfer.js b/Week4/homework/ex2/transfer.js new file mode 100644 index 000000000..36ca331d5 --- /dev/null +++ b/Week4/homework/ex2/transfer.js @@ -0,0 +1,107 @@ +// Week4/homework/ex2-transactions/transfer.js +import { MongoClient, ServerApiVersion } from "mongodb"; +import "dotenv/config"; + +const DB = "databaseWeek4"; +const COLL = "accounts"; + +export async function transfer({ from, to, amount, remark }) { + if (!Number.isFinite(amount) || amount <= 0) { + throw new Error("Amount must be a positive number"); + } + if (from === to) { + throw new Error("From and To accounts must be different"); + } + + const client = new MongoClient(process.env.MONGODB_URL, { + serverApi: ServerApiVersion.v1, + }); + await client.connect(); + + const session = client.startSession(); + try { + const col = client.db(DB).collection(COLL); + + const [a, b] = from < to ? [from, to] : [to, from]; + + const result = await session.withTransaction( + async () => { + const [accA, accB] = await Promise.all([ + col.findOne({ account_number: a }, { session }), + col.findOne({ account_number: b }, { session }), + ]); + if (!accA || !accB) throw new Error("Account not found"); + + const accFrom = accA.account_number === from ? accA : accB; + const accTo = accA.account_number === to ? accA : accB; + + if (accFrom.balance < amount) { + throw new Error("Insufficient funds"); + } + + const nextChangeFrom = + (accFrom.account_changes?.[accFrom.account_changes.length - 1] + ?.change_number ?? 0) + 1; + const nextChangeTo = + (accTo.account_changes?.[accTo.account_changes.length - 1] + ?.change_number ?? 0) + 1; + + const now = new Date(); + + const updFrom = await col.updateOne( + { _id: accFrom._id }, + { + $inc: { balance: -amount }, + $push: { + account_changes: { + change_number: nextChangeFrom, + amount: -amount, + changed_date: now, + remark, + }, + }, + }, + { session } + ); + if (updFrom.modifiedCount !== 1) { + throw new Error("Debit update failed"); + } + + const updTo = await col.updateOne( + { _id: accTo._id }, + { + $inc: { balance: amount }, + $push: { + account_changes: { + change_number: nextChangeTo, + amount, + changed_date: now, + remark, + }, + }, + }, + { session } + ); + if (updTo.modifiedCount !== 1) { + throw new Error("Credit update failed"); + } + }, + { + readConcern: { level: "snapshot" }, + writeConcern: { w: "majority" }, + readPreference: "primary", + } + ); + + if (result) { + console.log( + `transfer: success (from ${from} to ${to}, amount ${amount})` + ); + } else { + throw new Error("Transaction aborted by driver"); + } + } finally { + await session.endSession(); + await client.close(); + } +} diff --git a/Week4/package-lock.json b/Week4/package-lock.json new file mode 100644 index 000000000..7a3e9415a --- /dev/null +++ b/Week4/package-lock.json @@ -0,0 +1,176 @@ +{ + "name": "week4", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "week4", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "dotenv": "^17.2.2", + "mongodb": "^6.19.0" + } + }, + "node_modules/@mongodb-js/saslprep": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.3.0.tgz", + "integrity": "sha512-zlayKCsIjYb7/IdfqxorK5+xUMyi4vOKcFy10wKJYc63NSdKI8mNME+uJqfatkPmOSMMUiojrL58IePKBm3gvQ==", + "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": "11.0.5", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-11.0.5.tgz", + "integrity": "sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==", + "license": "MIT", + "dependencies": { + "@types/webidl-conversions": "*" + } + }, + "node_modules/bson": { + "version": "6.10.4", + "resolved": "https://registry.npmjs.org/bson/-/bson-6.10.4.tgz", + "integrity": "sha512-WIsKqkSC0ABoBJuT1LEX+2HEvNmNKKgnTAyd0fL8qzK4SH2i9NXg+t08YtdZp/V9IZ33cxe3iV4yM0qg8lMQng==", + "license": "Apache-2.0", + "engines": { + "node": ">=16.20.1" + } + }, + "node_modules/dotenv": { + "version": "17.2.2", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.2.2.tgz", + "integrity": "sha512-Sf2LSQP+bOlhKWWyhFsn0UsfdK/kCWRv1iuA2gXAwt3dyNabr6QSj00I2V10pidqz69soatm9ZwZvpQMTIOd5Q==", + "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": "6.19.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.19.0.tgz", + "integrity": "sha512-H3GtYujOJdeKIMLKBT9PwlDhGrQfplABNF1G904w6r5ZXKWyv77aB0X9B+rhmaAwjtllHzaEkvi9mkGVZxs2Bw==", + "license": "Apache-2.0", + "dependencies": { + "@mongodb-js/saslprep": "^1.1.9", + "bson": "^6.10.4", + "mongodb-connection-string-url": "^3.0.0" + }, + "engines": { + "node": ">=16.20.1" + }, + "peerDependencies": { + "@aws-sdk/credential-providers": "^3.188.0", + "@mongodb-js/zstd": "^1.1.0 || ^2.0.0", + "gcp-metadata": "^5.2.0", + "kerberos": "^2.0.1", + "mongodb-client-encryption": ">=6.0.0 <7", + "snappy": "^7.3.2", + "socks": "^2.7.1" + }, + "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": "3.0.2", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-3.0.2.tgz", + "integrity": "sha512-rMO7CGo/9BFwyZABcKAWL8UJwH/Kc2x0g72uhDWzG48URRax5TCIcJ7Rc3RZqffZzO/Gwff/jyKwCU9TN8gehA==", + "license": "Apache-2.0", + "dependencies": { + "@types/whatwg-url": "^11.0.2", + "whatwg-url": "^14.1.0 || ^13.0.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/package.json b/Week4/package.json new file mode 100644 index 000000000..e28edbcd7 --- /dev/null +++ b/Week4/package.json @@ -0,0 +1,17 @@ +{ + "name": "week4", + "version": "1.0.0", + "description": "## Agenda", + "main": "index.js", + "type": "module", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "dotenv": "^17.2.2", + "mongodb": "^6.19.0" + } +}