const { MongoClient } = require('mongodb');
// 连接URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
// 连接到MongoDB服务器
async function connectToMongo() {
try {
await client.connect();
console.log('Connected successfully to server');
} catch (err) {
console.error('Error connecting to MongoDB server:', err);
}
}
// 关闭连接
async function closeConnection() {
try {
await client.close();
console.log('Connection closed successfully');
} catch (err) {
console.error('Error closing the connection:', err);
}
}
// 获取数据库
function getDatabase(dbName) {
return client.db(dbName);
}
// 获取集合
function getCollection(dbName, collectionName) {
return client.db(dbName).collection(collectionName);
}
// 插入文档
async function insertOneDocument(dbName, collectionName, document) {
const collection = getCollection(dbName, collectionName);
const result = await collection.insertOne(document);
console.log('Inserted document:', result);
}
// 查询文档
async function findDocuments(dbName, collectionName, query) {
const collection = getCollection(dbName, collectionName);
const docs = await collection.find(query).toArray();
console.log('Found documents:', docs);
return docs;
}
// 更新文档
async function updateOneDocument(dbName, collectionName, filter, update) {
const collection = getCollection(dbName, collectionName);
const result = await collection.updateOne(filter, update);
console.log('Updated document:', result);
}
// 删除文档
async function deleteOneDocument(dbName, collectionName, filter) {
const collection = getCollection(dbName, collectionName);
const result = await collection.deleteOne(filter);
console.log('Deleted document:', result);
}
// 使用示例
async function run() {
await connectToMongo();
const dbName = 'mydatabase';
const collectionName = 'mycollection';
// 插入文档
const newDocument = { name: 'John Doe', age: 30 };
await insertOneDocument(dbName, collectionName, newDocument);
// 查询文档
const query = { age: 30 };
const docs = await findDocuments(dbName, collectionName, query);
// 更新文档
const update = { $set: { age: 35 } };
await updateOneDocument(dbName, collectionName, { name: 'John Doe' }, update);
// 删除文档
await deleteOneDocument(dbName, collectionName, { name: 'John Do
评论已关闭