diff --git a/Week4/homework/ex1-aggregation/.gitignore b/Week4/homework/ex1-aggregation/.gitignore new file mode 100644 index 000000000..2eea525d8 --- /dev/null +++ b/Week4/homework/ex1-aggregation/.gitignore @@ -0,0 +1 @@ +.env \ No newline at end of file diff --git a/Week4/homework/ex1-aggregation/exercise1_population.js b/Week4/homework/ex1-aggregation/exercise1_population.js new file mode 100644 index 000000000..40998796e --- /dev/null +++ b/Week4/homework/ex1-aggregation/exercise1_population.js @@ -0,0 +1,146 @@ +require('dotenv').config(); +const { MongoClient } = require('mongodb'); +const fs = require('fs'); +const csv = require('csv-parser'); + +const DB_NAME = "databaseWeek4"; +const COLLECTION_NAME = "population"; + +async function importCSV() { + const client = new MongoClient(process.env.MONGO_URI); + try { + await client.connect(); + const db = client.db(DB_NAME); + const collection = db.collection(COLLECTION_NAME); + + + await collection.deleteMany({}); + console.log('Collection cleared'); + + const results = []; + + return new Promise((resolve, reject) => { + fs.createReadStream('population_pyramid_1950-2022.csv') + .pipe(csv()) + .on('data', (data) => { + + data.M = parseInt(data.M); + data.F = parseInt(data.F); + data.Year = parseInt(data.Year); + results.push(data); + }) + .on('end', async () => { + try { + if (results.length > 0) { + await collection.insertMany(results); + console.log(`Data imported successfully: ${results.length} documents`); + } + await client.close(); + resolve(); + } catch (err) { + await client.close(); + reject(err); + } + }) + .on('error', async (err) => { + await client.close(); + reject(err); + }); + }); + } catch (err) { + console.error('Import error:', err); + await client.close(); + throw err; + } +} + +async function totalPopulationByCountry(countryName) { + const client = new MongoClient(process.env.MONGO_URI); + try { + await client.connect(); + const db = client.db(DB_NAME); + const collection = db.collection(COLLECTION_NAME); + + const results = await collection.aggregate([ + { $match: { Country: countryName } }, + { + $group: { + _id: "$Year", + countPopulation: { $sum: { $add: ["$M", "$F"] } } + } + }, + { $sort: { _id: 1 } } + ]).toArray(); + + console.log(`\nTotal population for ${countryName}:`); + console.log(JSON.stringify(results, null, 2)); + return results; + + } catch (err) { + console.error('Error in totalPopulationByCountry:', err); + return []; + } finally { + await client.close(); + } +} + +async function continentPopulation(yearValue, ageValue) { + const client = new MongoClient(process.env.MONGO_URI); + try { + await client.connect(); + const db = client.db(DB_NAME); + const collection = db.collection(COLLECTION_NAME); + + const results = await collection.aggregate([ + { + $match: { + Year: yearValue, + Age: ageValue, + Country: { + $in: [ + "AFRICA", + "ASIA", + "EUROPE", + "LATIN AMERICA AND THE CARIBBEAN", + "NORTHERN AMERICA", + "OCEANIA" + ] + } + } + }, + { + $project: { + Country: 1, + Year: 1, + Age: 1, + M: 1, + F: 1, + TotalPopulation: { $add: ["$M", "$F"] } + } + } + ]).toArray(); + + console.log(`\nContinent population for year ${yearValue}, age ${ageValue}:`); + console.log(JSON.stringify(results, null, 2)); + return results; + + } catch (err) { + console.error('Error in continentPopulation:', err); + return []; + } finally { + await client.close(); + } +} + +async function main() { + try { + // await importCSV(); + await totalPopulationByCountry("Netherlands"); + await continentPopulation(2020, "100+"); + + } catch (err) { + console.error('Main error:', err); + } +} + +main(); \ No newline at end of file diff --git a/Week4/homework/ex1-aggregation/exercise2_population.js b/Week4/homework/ex1-aggregation/exercise2_population.js new file mode 100644 index 000000000..f24abaae8 --- /dev/null +++ b/Week4/homework/ex1-aggregation/exercise2_population.js @@ -0,0 +1,41 @@ +require('dotenv').config(); +const { MongoClient } = require("mongodb"); + +const uri = process.env.MONGO_URI; +const client = new MongoClient(uri); + +async function continentPopulation(yearValue, ageValue) { + try { + await client.connect(); + const db = client.db("databaseWeek4"); + const collection = db.collection("population"); + + const results = await collection.aggregate([ + { + $match: { + Year: yearValue, + Age: ageValue, + Country: { $in: ["AFRICA", "ASIA", "EUROPE", "LATIN AMERICA AND THE CARIBBEAN", "NORTHERN AMERICA", "OCEANIA"] } + } + }, + { + $project: { + Country: 1, + Year: 1, + Age: 1, + M: 1, + F: 1, + TotalPopulation: { $add: ["$M", "$F"] } + } + } + ]).toArray(); + + console.log(results); + } catch (err) { + console.error(err); + } finally { + await client.close(); + } +} + +continentPopulation(2020, "100+"); diff --git a/Week4/homework/ex1-aggregation/package-lock.json b/Week4/homework/ex1-aggregation/package-lock.json new file mode 100644 index 000000000..0fc6b06b7 --- /dev/null +++ b/Week4/homework/ex1-aggregation/package-lock.json @@ -0,0 +1,192 @@ +{ + "name": "ex1-aggregation", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "ex1-aggregation", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "csv-parser": "^3.2.0", + "dotenv": "^17.2.3", + "mongodb": "^7.0.0" + } + }, + "node_modules/@mongodb-js/saslprep": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.3.2.tgz", + "integrity": "sha512-QgA5AySqB27cGTXBFmnpifAi7HxoGUeezwo6p9dI03MuDB6Pp33zgclqVb6oVK3j6I9Vesg0+oojW2XxB59SGg==", + "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/csv-parser": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/csv-parser/-/csv-parser-3.2.0.tgz", + "integrity": "sha512-fgKbp+AJbn1h2dcAHKIdKNSSjfp43BZZykXsCjzALjKy80VXQNHPFJ6T9Afwdzoj24aMkq8GwDS7KGcDPpejrA==", + "license": "MIT", + "bin": { + "csv-parser": "bin/csv-parser" + }, + "engines": { + "node": ">= 10" + } + }, + "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..12786a8aa --- /dev/null +++ b/Week4/homework/ex1-aggregation/package.json @@ -0,0 +1,17 @@ +{ + "name": "ex1-aggregation", + "version": "1.0.0", + "description": "", + "main": "exercise1_population.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "csv-parser": "^3.2.0", + "dotenv": "^17.2.3", + "mongodb": "^7.0.0" + } +} diff --git a/Week4/homework/ex1-aggregation/results/ex1.png b/Week4/homework/ex1-aggregation/results/ex1.png new file mode 100644 index 000000000..e5bc9b12a Binary files /dev/null and b/Week4/homework/ex1-aggregation/results/ex1.png differ diff --git a/Week4/homework/ex1-aggregation/results/ex2.png b/Week4/homework/ex1-aggregation/results/ex2.png new file mode 100644 index 000000000..2b2c905c7 Binary files /dev/null and b/Week4/homework/ex1-aggregation/results/ex2.png differ diff --git a/Week4/homework/ex1-aggregation/results/ex3.png b/Week4/homework/ex1-aggregation/results/ex3.png new file mode 100644 index 000000000..7e876e641 Binary files /dev/null and b/Week4/homework/ex1-aggregation/results/ex3.png differ diff --git a/Week4/homework/ex2-transactions/index.js b/Week4/homework/ex2-transactions/index.js new file mode 100644 index 000000000..f5b3f0dc7 --- /dev/null +++ b/Week4/homework/ex2-transactions/index.js @@ -0,0 +1,9 @@ +const { setup } = require("./setup"); +const { transfer } = require("./transfer"); + +async function start() { + await setup(); + await transfer(101, 102, 1000, "Test transfer"); +} + +start(); diff --git a/Week4/homework/ex2-transactions/package-lock.json b/Week4/homework/ex2-transactions/package-lock.json new file mode 100644 index 000000000..9a236dad4 --- /dev/null +++ b/Week4/homework/ex2-transactions/package-lock.json @@ -0,0 +1,180 @@ +{ + "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" + }, + "devDependencies": {} + }, + "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..52fc72f07 --- /dev/null +++ b/Week4/homework/ex2-transactions/package.json @@ -0,0 +1,16 @@ +{ + "name": "ex2-transactions", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "dotenv": "^17.2.3", + "mongodb": "^7.0.0" + } +} diff --git a/Week4/homework/ex2-transactions/results/ex1.png b/Week4/homework/ex2-transactions/results/ex1.png new file mode 100644 index 000000000..72a4970ec Binary files /dev/null and b/Week4/homework/ex2-transactions/results/ex1.png differ diff --git a/Week4/homework/ex2-transactions/setup.js b/Week4/homework/ex2-transactions/setup.js new file mode 100644 index 000000000..4bfb15f82 --- /dev/null +++ b/Week4/homework/ex2-transactions/setup.js @@ -0,0 +1,44 @@ +require("dotenv/config"); +const { MongoClient } = require("mongodb"); + +const uri = process.env.MONGO_URI; +const client = new MongoClient(uri); + +async function setup() { + const session = client.startSession(); + + try { + await client.connect(); + + await session.withTransaction(async () => { + const db = client.db("dbWeek4"); + const accounts = db.collection("accounts"); + + await accounts.deleteMany({}, { session }); + + await accounts.insertMany([ + { + account_number: 101, + balance: 5000, + account_changes: [] + }, + { + account_number: 102, + balance: 2000, + account_changes: [] + } + ], { session }); + }); + + console.log("Setup complete! Accounts created."); + } catch (err) { + console.error(err); + } finally { + await session.endSession(); + await client.close(); + } +} + +module.exports = { setup }; + +if (require.main === module) setup(); diff --git a/Week4/homework/ex2-transactions/transfer.js b/Week4/homework/ex2-transactions/transfer.js new file mode 100644 index 000000000..0c271b3ab --- /dev/null +++ b/Week4/homework/ex2-transactions/transfer.js @@ -0,0 +1,65 @@ +require("dotenv/config"); +const { MongoClient } = require("mongodb"); + +const client = new MongoClient(process.env.MONGO_URI); + +async function transfer(from, to, amount, remark) { + const session = client.startSession(); + + try { + await session.withTransaction(async () => { + const db = client.db("dbWeek4"); + const accounts = db.collection("accounts"); + + const accFrom = await accounts.findOne({ account_number: from }, { session }); + const accTo = await accounts.findOne({ account_number: to }, { session }); + + if (!accFrom || !accTo) throw new Error("No account found"); + if (accFrom.balance < amount) throw new Error("Not enough money"); + + const lastChangeFrom = accFrom.account_changes.at(-1)?.change_number || 0; + const lastChangeTo = accTo.account_changes.at(-1)?.change_number || 0; + + await accounts.updateOne( + { account_number: from }, + { + $inc: { balance: -amount }, + $push: { + account_changes: { + change_number: lastChangeFrom + 1, + amount: -amount, + changed_date: new Date(), + remark + } + } + }, + { session } + ); + + await accounts.updateOne( + { account_number: to }, + { + $inc: { balance: amount }, + $push: { + account_changes: { + change_number: lastChangeTo + 1, + amount: amount, + changed_date: new Date(), + remark + } + } + }, + { session } + ); + }); + + console.log(`Transferred ${amount} from ${from} to ${to}`); + } catch (err) { + console.error("Transaction aborted:", err); + } finally { + await session.endSession(); + await client.close(); + } +} + +module.exports = { transfer }; diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 000000000..e74e0a2d6 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,162 @@ +{ + "name": "databases-cohort54", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "mongodb": "^7.0.0" + } + }, + "node_modules/@mongodb-js/saslprep": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.3.2.tgz", + "integrity": "sha512-QgA5AySqB27cGTXBFmnpifAi7HxoGUeezwo6p9dI03MuDB6Pp33zgclqVb6oVK3j6I9Vesg0+oojW2XxB59SGg==", + "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/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/package.json b/package.json new file mode 100644 index 000000000..af87bd6da --- /dev/null +++ b/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "mongodb": "^7.0.0" + } +}