Here are some basic CRUD (Create, Read, Update, Delete) examples using MongoDB, assuming you’re interacting with it using the MongoDB Node.js driver:
Prerequisites:
- Make sure you have MongoDB installed and running locally or accessible via a remote connection.
- Install the MongoDB Node.js driver using npm:
npm install mongodb
CRUD Examples:
1. Connecting to MongoDB:
const { MongoClient } = require('mongodb');
// Connection URI
const uri = 'mongodb://localhost:27017';
// Database Name
const dbName = 'mydatabase';
// Create a new MongoClient
const client = new MongoClient(uri);
// Function to perform operations
async function main() {
try {
// Connect the client to the server
await client.connect();
console.log('Connected to MongoDB');
const database = client.db(dbName);
// Perform CRUD operations here...
} finally {
// Close the connection
await client.close();
}
}
main().catch(console.error);
2. Inserting a Document:
const collection = database.collection('mycollection');
const document = { name: 'John Doe', age: 30 };
const result = await collection.insertOne(document);
console.log('${result.insertedCount} documents inserted with the _id: ${result.insertedId}');
3. Finding Documents:
const documents = await collection.find({}).toArray();
console.log('Found documents:', documents);
4. Updating a Document:
const filter = { name: 'John Doe' };
const updateDocument = {
$set: { age: 31 }
};
const result = await collection.updateOne(filter, updateDocument);
console.log('${result.modifiedCount} document(s) updated');
5. Deleting a Document:
const deleteFilter = { name: 'John Doe' };
const result = await collection.deleteOne(deleteFilter);
console.log('${result.deletedCount} document(s) deleted');
These are basic examples to get you started with MongoDB CRUD operations using the Node.js driver. Remember to handle errors appropriately in your production code.

Ankit Srivastava is an IT trainer, technology educator, and digital skills mentor with expertise in programming, data analytics, AI, and software development. He has successfully trained thousands of learners, with more than 10,000 student enrollments on Udemy. His practical teaching approach empowers students and professionals to build in-demand technical skills. Colorstech channel where Ankit posts video tutorials has more than 8000 Subscribers.