3. CRUD Operations: Create, Read, Update, Delete
Mastering MongoDB CRUD Operations
CRUD (Create, Read, Update, Delete) is the foundation of database operations. MongoDB provides a rich set of operations for each CRUD category. Understanding these operations is essential for building efficient applications.
MongoDB's CRUD operations are designed for the document model. Insert operations add documents to collections. Query operations find documents using filters, projections, and sorting. Update operations modify documents using update operators. Delete operations remove documents. MongoDB also supports bulk operations for efficiency. Understanding CRUD operations is essential for building applications. The MongoDB query language is powerful and flexible. It supports a wide range of operators and options.
Insert Operations
Insert operations add new documents to collections. The insertOne method inserts a single document. The insertMany method inserts multiple documents. Both methods return the inserted document IDs. Insert operations validate the data and generate an _id if not provided. You can insert documents with any structure. MongoDB does not enforce a schema at the database level. This flexibility is a key advantage of the document model.
import { MongoClient } from 'mongodb'; const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const db = client.db('mydb'); const collection = db.collection('users'); // Insert one document const result = await collection.insertOne({ name: 'Alice', email: 'alice@example.com', age: 30, createdAt: new Date() }); console.log('Inserted ID:', result.insertedId); // Insert multiple documents const results = await collection.insertMany([ { name: 'Bob', email: 'bob@example.com', age: 25 }, { name: 'Charlie', email: 'charlie@example.com', age: 35 } ]); console.log('Inserted IDs:', results.insertedIds);
Query Operations
Query operations find documents in a collection. The find method returns a cursor that you can iterate. You can filter documents using a query document. You can project specific fields using a projection document. You can sort, skip, and limit results. MongoDB supports a wide range of query operators, including comparison operators ($eq, $ne, $gt, $lt), logical operators ($and, $or, $not), and array operators ($in, $all, $size).
// Find all users const users = await collection.find({}).toArray(); // Find with filter const adults = await collection.find({ age: { $gte: 18 } }).toArray(); // Find with projection (only name and email) const names = await collection.find( { age: { $gte: 18 } }, { projection: { name: 1, email: 1, _id: 0 } } ).toArray(); // Find with sorting, skip, limit const sorted = await collection.find({}) .sort({ age: -1 }) .skip(10) .limit(5) .toArray(); // Find with logical operators const filtered = await collection.find({ $or: [ { age: { $lt: 20 } }, { age: { $gt: 50 } } ] }).toArray(); // Find with array operators const withTag = await collection.find({ tags: { $in: ['mongodb', 'database'] } }).toArray();
Update Operations
Update operations modify existing documents. The updateOne method updates the first matching document. The updateMany method updates all matching documents. Update operations use update operators to specify changes. The $set operator sets field values. The $inc operator increments numeric values. The $push operator adds elements to arrays. The $addToSet operator adds elements to arrays only if they don't exist. The $unset operator removes fields. Update operations can also replace entire documents.
// Update one document with $set await collection.updateOne( { name: 'Alice' }, { $set: { age: 31, email: 'alice.new@example.com' } } ); // Update many with $inc await collection.updateMany( { age: { $lt: 30 } }, { $inc: { age: 1 } } ); // Add to array with $push await collection.updateOne( { name: 'Alice' }, { $push: { tags: 'mongodb' } } ); // Add to array only if not exists await collection.updateOne( { name: 'Alice' }, { $addToSet: { tags: 'database' } } ); // Remove field with $unset await collection.updateOne( { name: 'Alice' }, { $unset: { tempField: '' } } ); // Replace document await collection.replaceOne( { name: 'Alice' }, { name: 'Alice', email: 'alice@example.com', age: 31 } );
Delete Operations
Delete operations remove documents from collections. The deleteOne method removes the first matching document. The deleteMany method removes all matching documents. You can also delete all documents in a collection using deleteMany without a filter. Delete operations are permanent — use them carefully.
// Delete one document await collection.deleteOne({ name: 'Alice' }); // Delete many documents await collection.deleteMany({ age: { $lt: 18 } }); // Delete all documents await collection.deleteMany({});
Knowledge Check
Ready to test your understanding of 3. CRUD Operations: Create, Read, Update, Delete?