const { MongoClient } = require('mongodb');
// Connection URL
const url = 'mongodb://127.0.0.1:27017';
// Database Name
const dbName = 'ecomm';
// Create a new document
async function createDocument(collection, document) {
const client = await MongoClient.connect(url);
const db = client.db(dbName);
const result = await db.collection(collection).insertOne(document);
console.log('Document created:', result.insertedId);
client.close();
}
// Read documents
async function readDocuments(collection, query) {
const client = await MongoClient.connect(url);
const db = client.db(dbName);
const documents = await db.collection(collection).find(query).toArray();
console.log('Documents found:', documents);
client.close();
}
// Update a document
async function updateDocument(collection, filter, update) {
const client = await MongoClient.connect(url);
const db = client.db(dbName);
const result = await db.collection(collection).updateOne(filter, update);
console.log('Document updated:', result.modifiedCount);
client.close();
}
// Delete a document
async function deleteDocument(collection, filter) {
const client = await MongoClient.connect(url);
const db = client.db(dbName);
const result = await db.collection(collection).deleteOne(filter);
console.log('Document deleted:', result.deletedCount);
client.close();
}
// Usage crud
createDocument('users', { name: 'John Doe', age: 30 });
readDocuments('users', { age: { $gte: 25 } });
updateDocument('users', { name: 'John Doe' }, { $set: { age: 35 } });
//deleteDocument('users', { name: 'John Doe' });
0 Comments