Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Node.js with MongoDB: Database, Collections, and CRUD

Lesson 42 of 46 in the free Web Technologies notes on Siksha Sarovar, written by Rohit Jangra.

Node.js with MongoDB: Database, Collections, and CRUD

What is MongoDB?

MongoDB is a NoSQL, document-oriented database. Instead of tables and rows, it stores data as flexible JSON-like documents (BSON) grouped into collections inside a database.

RDBMS TermMongoDB Equivalent
DatabaseDatabase
TableCollection
RowDocument
ColumnField

Connecting Node.js to MongoDB

npm install mongodb
const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);

async function main() {
    await client.connect();
    console.log('Connected to MongoDB');

    // Create/select a database
    const db = client.db('schoolDB');

    // Create/select a collection
    const students = db.collection('students');

    // ... CRUD operations go here

    await client.close();
}

main().catch(console.error);

MongoDB creates the database and collection automatically the first time data is written to them — no explicit CREATE DATABASE step is required.

Insert

// Insert one document
await students.insertOne({ name: 'Alice', age: 20, course: 'CSE' });

// Insert many documents
await students.insertMany([
    { name: 'Bob', age: 22, course: 'IT' },
    { name: 'Carol', age: 21, course: 'CSE' }
]);

Query (Find)

// Find all documents
const all = await students.find({}).toArray();

// Find with a filter
const cseStudents = await students.find({ course: 'CSE' }).toArray();

// Find one document
const alice = await students.findOne({ name: 'Alice' });

// Query operators
const adults = await students.find({ age: { $gte: 18 } }).toArray();

Common Query Operators

OperatorMeaning
$eqEqual to
$gt / $gteGreater than / or equal
$lt / $lteLess than / or equal
$inValue in a list
$and / $orLogical AND / OR

Update

// Update one document
await students.updateOne(
    { name: 'Alice' },
    { $set: { age: 21 } }
);

// Update many documents
await students.updateMany(
    { course: 'CSE' },
    { $set: { department: 'Computer Science' } }
);

Delete

// Delete one document
await students.deleteOne({ name: 'Bob' });

// Delete many documents
await students.deleteMany({ course: 'IT' });

Sort

// Sort by age ascending (1) or descending (-1)
const byAgeAsc = await students.find({}).sort({ age: 1 }).toArray();
const byAgeDesc = await students.find({}).sort({ age: -1 }).toArray();

Join (Aggregation with $lookup)

MongoDB is not relational, but it supports join-like operations using $lookup in the aggregation pipeline:

const results = await db.collection('orders').aggregate([
    {
        $lookup: {
            from: 'students',       // collection to join
            localField: 'studentId', // field in "orders"
            foreignField: '_id',     // field in "students"
            as: 'studentDetails'
        }
    }
]).toArray();

Full CRUD Example

async function run() {
    const db = client.db('schoolDB');
    const students = db.collection('students');

    await students.insertOne({ name: 'Dave', age: 23, course: 'ECE' });
    const found = await students.find({ course: 'ECE' }).sort({ age: -1 }).toArray();
    await students.updateOne({ name: 'Dave' }, { $set: { age: 24 } });
    await students.deleteOne({ name: 'Dave' });

    console.log(found);
}
Key Takeaway: MongoDB stores flexible JSON-like documents in collections rather than rigid tables. The official mongodb driver exposes insertOne/Many, find, updateOne/Many, deleteOne/Many, .sort(), and $lookup (for join-like queries) — all through simple, promise-based async calls.