// projects.mongodb
10 Best MongoDB Projects
Hand-picked and ordered easiest → hardest — each with complete code and expected output. Build these to turn lessons into a portfolio.
Back to MongoDB course
// solution.code
mongodb
// Personal Contact Manager - MongoDB CRUD Operations
// Prerequisites: MongoDB running locally, Node.js with mongodb driver installed
// Run: npm install mongodb
const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
async function main() {
try {
await client.connect();
console.log('Connected to MongoDB');
const db = client.db('contactManager');
const contacts = db.collection('contacts');
// Clear existing data for demo
await contacts.deleteMany({});
// CREATE - Insert contacts
const insertResult = await contacts.insertMany([
{ name: 'John Doe', phone: '555-1234', email: 'john@example.com' },
{ name: 'Jane Smith', phone: '555-5678', email: 'jane@example.com' },
{ name: 'Bob Johnson', phone: '555-9012', email: 'bob@example.com' }
]);
console.log('\nInserted contacts:', insertResult.insertedCount);
// READ - Find all contacts
console.log('\nAll Contacts:');
const allContacts = await contacts.find({}).toArray();
allContacts.forEach(c => console.log(` ${c.name} - ${c.phone} - ${c.email}`));
// READ - Find specific contact
console.log('\nFind contact named "Jane Smith":');
const jane = await contacts.findOne({ name: 'Jane Smith' });
console.log(` ${jane.name} - ${jane.phone}`);
// UPDATE - Update contact phone number
const updateResult = await contacts.updateOne(
{ name: 'John Doe' },
{ $set: { phone: '555-9999' } }
);
console.log('\nUpdated John\'s phone. Modified count:', updateResult.modifiedCount);
// Verify update
const updatedJohn = await contacts.findOne({ name: 'John Doe' });
console.log(` Updated: ${updatedJohn.name} - ${updatedJohn.phone}`);
// DELETE - Remove a contact
const deleteResult = await contacts.deleteOne({ name: 'Bob Johnson' });
console.log('\nDeleted Bob. Deleted count:', deleteResult.deletedCount);
// Final count
const finalCount = await contacts.countDocuments();
console.log('\nFinal contact count:', finalCount);
} finally {
await client.close();
console.log('\nConnection closed');
}
}
main().catch(console.error); output
Connected to MongoDB Inserted contacts: 3 All Contacts: John Doe - 555-1234 - john@example.com Jane Smith - 555-5678 - jane@example.com Bob Johnson - 555-9012 - bob@example.com Find contact named "Jane Smith": Jane Smith - 555-5678 Updated John's phone. Modified count: 1 Updated: John Doe - 555-9999 Deleted Bob. Deleted count: 1 Final contact count: 2 Connection closed
