CRUD Operations with MongoDB
Now that you know how to connect to MongoDB, let's perform the four basic operations: **Create, Read, Update, and Delete** – commonly known as CRUD. These are the foundation of any database-driven application.
Setup: Get the Collection
First, let's assume we have a database connection and a collection to work with:
const { MongoClient } = require('mongodb');const url = 'mongodb://localhost:27017';const dbName = 'myapp';
const client = new MongoClient(url);
async function getCollection() { await client.connect(); const db = client.db(dbName); return db.collection('users');}Think of CRUD as the basic actions you can do with any data: Create a new record, Read existing records, Update records, and Delete records.
CREATE: Inserting Documents
Insert One Document
const collection = await getCollection();
const user = { name: 'Alice Johnson', email: 'alice@example.com', age: 28, hobbies: ['reading', 'swimming']};
const result = await collection.insertOne(user);console.log('Inserted ID:', result.insertedId);Insert Multiple Documents
const users = [ { name: 'Bob', email: 'bob@example.com', age: 35 }, { name: 'Charlie', email: 'charlie@example.com', age: 42 }, { name: 'Diana', email: 'diana@example.com', age: 31 }];
const result = await collection.insertMany(users);console.log('Inserted count:', result.insertedCount);READ: Finding Documents
Find All Documents
const collection = await getCollection();
<!-- Get all documents -->const allUsers = await collection.find({}).toArray();console.log('All users:', allUsers);Find with Filter
<!-- Find users older than 30 -->const olderUsers = await collection .find({ age: { $gt: 30 } }) .toArray();
<!-- Find users with specific name -->const bob = await collection.findOne({ name: 'Bob' });Query Operators
| Operator | Meaning |
|---|---|
| `$gt` | Greater than |
| `$gte` | Greater than or equal |
| `$lt` | Less than |
| `$lte` | Less than or equal |
| `$in` | Matches any value in array |
UPDATE: Modifying Documents
Update One Document
<!-- Find user with name 'Alice' and update age -->const result = await collection.updateOne( { name: 'Alice Johnson' }, { $set: { age: 29 } });
console.log('Modified count:', result.modifiedCount);Update Multiple Documents
<!-- Add a new field to all users -->const result = await collection.updateMany( {}, <!-- empty filter matches all --> { $set: { active: true } });console.log('Modified count:', result.modifiedCount);DELETE: Removing Documents
Delete One Document
const result = await collection.deleteOne({ name: 'Charlie' });console.log('Deleted count:', result.deletedCount);Delete Multiple Documents
<!-- Delete all users younger than 25 -->const result = await collection.deleteMany({ age: { $lt: 25 } });console.log('Deleted count:', result.deletedCount);Complete Example in a Server
Here's how you might use these operations in an HTTP server:
const http = require('http');
const server = http.createServer(async (req, res) => { const collection = await getCollection(); if (req.url === '/api/users' && req.method === 'GET') { const users = await collection.find({}).toArray(); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(users)); } <!-- Handle POST request to create user --> if (req.url === '/api/users' && req.method === 'POST') { let body = ''; req.on('data', chunk => body += chunk); req.on('end', async () => { const newUser = JSON.parse(body); const result = await collection.insertOne(newUser); res.writeHead(201); res.end(JSON.stringify({ id: result.insertedId })); }); }});Two Minute Drill
- CRUD = Create, Read, Update, Delete
- Create: `insertOne()`, `insertMany()`
- Read: `find()`, `findOne()` with query filters
- Update: `updateOne()`, `updateMany()` with `$set` operator
- Delete: `deleteOne()`, `deleteMany()`
- Use query operators like `$gt`, `$lt` for powerful queries
Need more clarification?
Drop us an email at career@quipoinfotech.com
