Skip to content

Commit 45bfc1a

Browse files
committed
fix
1 parent cdcf4ac commit 45bfc1a

File tree

10 files changed

+275
-89
lines changed

10 files changed

+275
-89
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.env
Lines changed: 131 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,146 @@
1-
const { MongoClient } = require("mongodb");
1+
require('dotenv').config();
2+
const { MongoClient } = require('mongodb');
3+
const fs = require('fs');
4+
const csv = require('csv-parser');
25

3-
const uri = "mongodb+srv://daryna2003tk_db_user:[email protected]/dbWeek4?retryWrites=true&w=majority";
4-
const client = new MongoClient(uri);
6+
const DB_NAME = "databaseWeek4";
7+
const COLLECTION_NAME = "population";
58

6-
async function totalPopulationByCountry(countryName) {
9+
async function importCSV() {
10+
const client = new MongoClient(process.env.MONGO_URI);
711
try {
812
await client.connect();
9-
const db = client.db("dbWeek4");
10-
const collection = db.collection("population");
13+
const db = client.db(DB_NAME);
14+
const collection = db.collection(COLLECTION_NAME);
15+
1116

12-
const cursor = collection.find({ Country: countryName });
13-
const populationByYear = {};
17+
await collection.deleteMany({});
18+
console.log('Collection cleared');
1419

15-
await cursor.forEach(doc => {
16-
const year = doc.Year;
17-
const total = doc.M + doc.F;
18-
if (!populationByYear[year]) populationByYear[year] = 0;
19-
populationByYear[year] += total;
20+
const results = [];
21+
22+
return new Promise((resolve, reject) => {
23+
fs.createReadStream('population_pyramid_1950-2022.csv')
24+
.pipe(csv())
25+
.on('data', (data) => {
26+
27+
data.M = parseInt(data.M);
28+
data.F = parseInt(data.F);
29+
data.Year = parseInt(data.Year);
30+
results.push(data);
31+
})
32+
.on('end', async () => {
33+
try {
34+
if (results.length > 0) {
35+
await collection.insertMany(results);
36+
console.log(`Data imported successfully: ${results.length} documents`);
37+
}
38+
await client.close();
39+
resolve();
40+
} catch (err) {
41+
await client.close();
42+
reject(err);
43+
}
44+
})
45+
.on('error', async (err) => {
46+
await client.close();
47+
reject(err);
48+
});
2049
});
50+
} catch (err) {
51+
console.error('Import error:', err);
52+
await client.close();
53+
throw err;
54+
}
55+
}
2156

22-
const result = Object.keys(populationByYear).sort().map(year => ({
23-
_id: parseInt(year),
24-
countPopulation: populationByYear[year]
25-
}));
57+
async function totalPopulationByCountry(countryName) {
58+
const client = new MongoClient(process.env.MONGO_URI);
59+
try {
60+
await client.connect();
61+
const db = client.db(DB_NAME);
62+
const collection = db.collection(COLLECTION_NAME);
63+
64+
const results = await collection.aggregate([
65+
{ $match: { Country: countryName } },
66+
{
67+
$group: {
68+
_id: "$Year",
69+
countPopulation: { $sum: { $add: ["$M", "$F"] } }
70+
}
71+
},
72+
{ $sort: { _id: 1 } }
73+
]).toArray();
2674

27-
console.log(result);
75+
console.log(`\nTotal population for ${countryName}:`);
76+
console.log(JSON.stringify(results, null, 2));
77+
return results;
2878

2979
} catch (err) {
30-
console.error(err);
80+
console.error('Error in totalPopulationByCountry:', err);
81+
return [];
3182
} finally {
32-
client.close();
83+
await client.close();
84+
}
85+
}
86+
87+
async function continentPopulation(yearValue, ageValue) {
88+
const client = new MongoClient(process.env.MONGO_URI);
89+
try {
90+
await client.connect();
91+
const db = client.db(DB_NAME);
92+
const collection = db.collection(COLLECTION_NAME);
93+
94+
const results = await collection.aggregate([
95+
{
96+
$match: {
97+
Year: yearValue,
98+
Age: ageValue,
99+
Country: {
100+
$in: [
101+
"AFRICA",
102+
"ASIA",
103+
"EUROPE",
104+
"LATIN AMERICA AND THE CARIBBEAN",
105+
"NORTHERN AMERICA",
106+
"OCEANIA"
107+
]
108+
}
109+
}
110+
},
111+
{
112+
$project: {
113+
Country: 1,
114+
Year: 1,
115+
Age: 1,
116+
M: 1,
117+
F: 1,
118+
TotalPopulation: { $add: ["$M", "$F"] }
119+
}
120+
}
121+
]).toArray();
122+
123+
console.log(`\nContinent population for year ${yearValue}, age ${ageValue}:`);
124+
console.log(JSON.stringify(results, null, 2));
125+
return results;
126+
127+
} catch (err) {
128+
console.error('Error in continentPopulation:', err);
129+
return [];
130+
} finally {
131+
await client.close();
132+
}
133+
}
134+
135+
async function main() {
136+
try {
137+
// await importCSV();
138+
await totalPopulationByCountry("Netherlands");
139+
await continentPopulation(2020, "100+");
140+
141+
} catch (err) {
142+
console.error('Main error:', err);
33143
}
34144
}
35145

36-
totalPopulationByCountry("Netherlands");
146+
main();

Week4/homework/ex1-aggregation/exercise2_population.js

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,40 @@
1+
require('dotenv').config();
12
const { MongoClient } = require("mongodb");
23

3-
const uri = "mongodb+srv://daryna2003tk_db_user:[email protected]/dbWeek4?retryWrites=true&w=majority";
4+
const uri = process.env.MONGO_URI;
45
const client = new MongoClient(uri);
56

67
async function continentPopulation(yearValue, ageValue) {
78
try {
89
await client.connect();
9-
const db = client.db("dbWeek4");
10+
const db = client.db("databaseWeek4");
1011
const collection = db.collection("population");
1112

1213
const results = await collection.aggregate([
13-
{ $match: { Year: yearValue, Age: ageValue, Country: { $in: ["AFRICA", "ASIA", "EUROPE", "LATIN AMERICA AND THE CARIBBEAN", "NORTHERN AMERICA", "OCEANIA"] } } },
14-
{ $project: { Country: 1, Year: 1, Age: 1, M: 1, F: 1, TotalPopulation: { $add: ["$M", "$F"] } } }
14+
{
15+
$match: {
16+
Year: yearValue,
17+
Age: ageValue,
18+
Country: { $in: ["AFRICA", "ASIA", "EUROPE", "LATIN AMERICA AND THE CARIBBEAN", "NORTHERN AMERICA", "OCEANIA"] }
19+
}
20+
},
21+
{
22+
$project: {
23+
Country: 1,
24+
Year: 1,
25+
Age: 1,
26+
M: 1,
27+
F: 1,
28+
TotalPopulation: { $add: ["$M", "$F"] }
29+
}
30+
}
1531
]).toArray();
1632

1733
console.log(results);
1834
} catch (err) {
1935
console.error(err);
2036
} finally {
21-
client.close();
37+
await client.close();
2238
}
2339
}
2440

Week4/homework/ex1-aggregation/package-lock.json

Lines changed: 26 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Week4/homework/ex1-aggregation/package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
"author": "",
1111
"license": "ISC",
1212
"dependencies": {
13+
"csv-parser": "^3.2.0",
14+
"dotenv": "^17.2.3",
1315
"mongodb": "^7.0.0"
1416
}
1517
}

Week4/homework/ex2-transactions/index.js

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ const { transfer } = require("./transfer");
33

44
async function start() {
55
await setup();
6-
76
await transfer(101, 102, 1000, "Test transfer");
87
}
98

Week4/homework/ex2-transactions/package-lock.json

Lines changed: 15 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Week4/homework/ex2-transactions/package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
"author": "",
1111
"license": "ISC",
1212
"dependencies": {
13+
"dotenv": "^17.2.3",
1314
"mongodb": "^7.0.0"
14-
},
15-
"devDependencies": {}
15+
}
1616
}
Lines changed: 27 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,44 @@
1+
require("dotenv/config");
12
const { MongoClient } = require("mongodb");
23

3-
const uri = "mongodb+srv://daryna2003tk_db_user:[email protected]/dbWeek4?retryWrites=true&w=majority";
4+
const uri = process.env.MONGO_URI;
45
const client = new MongoClient(uri);
56

67
async function setup() {
8+
const session = client.startSession();
9+
710
try {
811
await client.connect();
9-
const db = client.db("dbWeek4");
10-
const accounts = db.collection("accounts");
11-
12-
await accounts.deleteMany({});
13-
14-
await accounts.insertMany([
15-
{
16-
account_number: 101,
17-
balance: 5000,
18-
account_changes: []
19-
},
20-
{
21-
account_number: 102,
22-
balance: 2000,
23-
account_changes: []
24-
}
25-
]);
26-
27-
console.log("Everything complete! Accounts created.");
12+
13+
await session.withTransaction(async () => {
14+
const db = client.db("dbWeek4");
15+
const accounts = db.collection("accounts");
16+
17+
await accounts.deleteMany({}, { session });
18+
19+
await accounts.insertMany([
20+
{
21+
account_number: 101,
22+
balance: 5000,
23+
account_changes: []
24+
},
25+
{
26+
account_number: 102,
27+
balance: 2000,
28+
account_changes: []
29+
}
30+
], { session });
31+
});
32+
33+
console.log("Setup complete! Accounts created.");
2834
} catch (err) {
2935
console.error(err);
3036
} finally {
37+
await session.endSession();
3138
await client.close();
3239
}
3340
}
3441

3542
module.exports = { setup };
3643

37-
3844
if (require.main === module) setup();

0 commit comments

Comments
 (0)