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.