Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 110 additions & 0 deletions Week4/homework/ex1-aggregation/aggregation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
const { MongoClient, ServerApiVersion } = require("mongodb");
require("dotenv").config();
const uri = process.env.MONGODB_URL;


const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
});

async function run() {
try {
await client.connect();
console.log("Connected to MongoDB successfully!");

const db = client.db("databaseWeek4");
const collection = db.collection("population");
// =====================
// 1️⃣ Get population per country (example: Netherlands)
// =====================
const populationNetherlands = await getPopulationPerCountry(
collection,
"Netherlands"
);
console.log("\nPopulation per year for Netherlands:");
console.table(populationNetherlands);

// =====================
// 2️ Get population per continent for year & age
// =====================
const continentInfo2020 = await getContinentInfo(collection, 2020, "100+");
console.log("\nPopulation for continents in 2020 (age 100+):");
console.table(continentInfo2020);
} catch (err) {
console.error(err);
} finally {
await client.close();
console.log("MongoDB connection closed.");
}
}
run();

// =====================
// D1: Total population per country
// =====================
const getPopulationPerCountry = async (collection, country) => {
const pipeline = [
{ $match: { Country: country } },
{
$group: {
_id: "$Year",
countPopulation: { $sum: { $add: ["$M", "$F"] } },
},
},
{
$project: {
_id: 0,
Year: "$_id",
countPopulation: 1,
},
},
{ $sort: { Year: 1 } },
];

return await collection.aggregate(pipeline).toArray();
};

// D2: Total population per continent/year/age

const getContinentInfo = async (collection, year, age) => {
const pipeline = [
{
$match: {
Country: {
$in: [
"AFRICA",
"ASIA",
"EUROPE",
"LATIN AMERICA AND THE CARIBBEAN",
"NORTHERN AMERICA",
"OCEANIA",
],
},
Year: year,
Age: age,
},
},
{
$addFields: {
TotalPopulation: { $add: ["$M", "$F"] },
},
},
{
$project: {
_id: 0,
Country: 1,
Year: 1,
Age: 1,
M: 1,
F: 1,
TotalPopulation: 1,
},
},
];

return await collection.aggregate(pipeline).toArray();
};
13 changes: 13 additions & 0 deletions Week4/homework/ex2-transactions/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const { setupAccounts } = require("./setup");
const { transferMoney } = require("./transfer");

async function main() {

await setupAccounts();

await transferMoney(101, 102, 1000, "Homework test");

console.log("All operations completed!");
}

main();
39 changes: 39 additions & 0 deletions Week4/homework/ex2-transactions/setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const { MongoClient, ServerApiVersion } = require("mongodb");
require("dotenv").config();

const uri = process.env.MONGODB_URL;
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
});

async function setupAccounts() {
try {
await client.connect();
const db = client.db("databaseWeek4");
const collection = db.collection("accounts");

await collection.deleteMany({});

const accounts = [
{ account_number: 101, balance: 5000, account_changes: [] },
{ account_number: 102, balance: 3000, account_changes: [] }
];

await collection.insertMany(accounts);
console.log("Accounts setup completed!");
} catch (err) {
console.error(err);
} finally {
await client.close();
}
}

module.exports = { setupAccounts };

if (require.main === module) {
setupAccounts();
}
75 changes: 75 additions & 0 deletions Week4/homework/ex2-transactions/transfer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
const { MongoClient, ServerApiVersion } = require("mongodb");
require("dotenv").config();

const uri = process.env.MONGODB_URL;
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
});

async function transferMoney(fromAccount, toAccount, amount, remark) {
const session = client.startSession();
try {
await client.connect();
const db = client.db("databaseWeek4");
const collection = db.collection("accounts");

await session.withTransaction(async () => {

const from = await collection.findOne({ account_number: fromAccount }, { session });
const to = await collection.findOne({ account_number: toAccount }, { session });

if (!from || !to) throw new Error("Account not found");
if (from.balance < amount) throw new Error("Insufficient funds");

await collection.updateOne(
{ account_number: fromAccount },
{
$inc: { balance: -amount },
$push: {
account_changes: {
change_number: from.account_changes.length + 1,
amount: -amount,
changed_date: new Date(),
remark: remark
}
}
},
{ session }
);

await collection.updateOne(
{ account_number: toAccount },
{
$inc: { balance: amount },
$push: {
account_changes: {
change_number: to.account_changes.length + 1,
amount: amount,
changed_date: new Date(),
remark: remark
}
}
},
{ session }
);
});

console.log(`Transferred ${amount} from ${fromAccount} to ${toAccount}`);
} catch (err) {
console.error("Transaction failed:", err.message);
} finally {
await session.endSession();
await client.close();
}
}

module.exports = { transferMoney };


if (require.main === module) {
transferMoney(101, 102, 1000, "Test transfer");
}
Loading