Viewing: mongo_students.js
/**
* Simple MongoDB practice script.
* Run with: `MONGODB_URI="your-uri" node code/mongo_students.js`
*/
import { MongoClient } from 'mongodb';
const uri = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri, { family: 4 });
async function main() {
try {
await client.connect();
const db = client.db('yucai_school');
const students = db.collection('students');
// Seed practice data (tagged with testData so it is easy to remove).
const sampleStudents = [
{ name: 'Alice', gradeLevel: 11, gpa: 3.8, focus: ['SAT Math', 'AP Calc'], hoursPerWeek: 12, testData: true },
{ name: 'Ben', gradeLevel: 10, gpa: 3.2, focus: ['SAT Reading'], hoursPerWeek: 6, testData: true },
{ name: 'Cindy', gradeLevel: 12, gpa: 4.0, focus: ['AP Physics', 'SAT Math'], hoursPerWeek: 15, testData: true },
{ name: 'Daniel', gradeLevel: 9, gpa: 3.5, focus: ['Algebra II'], hoursPerWeek: 5, testData: true }
];
await students.deleteMany({ testData: true });
await students.insertMany(sampleStudents);
const honorStudents = await students
.find({ gpa: { $gte: 3.5 } }, { projection: { _id: 0, name: 1, gpa: 1, focus: 1 } })
.sort({ gpa: -1 })
.toArray();
const hoursByGrade = await students
.aggregate([
{ $match: { testData: true } },
{ $group: { _id: '$gradeLevel', avgHours: { $avg: '$hoursPerWeek' }, totalStudents: { $sum: 1 } } },
{ $sort: { _id: 1 } }
])
.toArray();
const updateResult = await students.updateOne(
{ name: 'Alice' },
{ $set: { counselor: 'Ms. Lee', updatedAt: new Date() } }
);
const homeworkPlan = await students
.aggregate([
{ $match: { testData: true } },
{ $unwind: '$focus' },
{ $group: { _id: '$focus', students: { $push: '$name' }, count: { $sum: 1 } } },
{ $sort: { count: -1 } }
])
.toArray();
console.log('Honor students (GPA ≥ 3.5):', honorStudents);
console.log('Average weekly hours by grade:', hoursByGrade);
console.log('Updated Alice profile?', updateResult.modifiedCount === 1);
console.log('Homework plan grouped by focus:', homeworkPlan);
} finally {
await client.close();
}
}
main().catch((err) => {
console.error('MongoDB script failed:', err);
process.exitCode = 1;
});
Close