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
76 changes: 76 additions & 0 deletions Week4/homework/ex1-aggregation/index.js
Original file line number Diff line number Diff line change
@@ -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);
48 changes: 48 additions & 0 deletions Week4/homework/ex2/index.js
Original file line number Diff line number Diff line change
@@ -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);
56 changes: 56 additions & 0 deletions Week4/homework/ex2/setup.js
Original file line number Diff line number Diff line change
@@ -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);
}
107 changes: 107 additions & 0 deletions Week4/homework/ex2/transfer.js
Original file line number Diff line number Diff line change
@@ -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];

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: use better names for a and b. It is hard to understand what they are for in the first sight.


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();
}
}
Loading