推荐答案
在 Node.js 中操作 MongoDB 数据库通常使用 mongodb 官方提供的 Node.js 驱动程序或 mongoose 这样的 ODM(对象文档映射)库。以下是使用 mongodb 官方驱动程序的示例代码:
// www.javascriptcn.com code example
const { MongoClient } = require('mongodb');
async function main() {
const uri = 'mongodb://localhost:27017'; // MongoDB 连接字符串
const client = new MongoClient(uri);
try {
await client.connect(); // 连接到 MongoDB
const database = client.db('mydatabase'); // 选择数据库
const collection = database.collection('mycollection'); // 选择集合
// 插入文档
const insertResult = await collection.insertOne({ name: 'John', age: 30 });
console.log('Inserted document:', insertResult.insertedId);
// 查询文档
const query = { name: 'John' };
const findResult = await collection.findOne(query);
console.log('Found document:', findResult);
// 更新文档
const updateResult = await collection.updateOne(query, { $set: { age: 31 } });
console.log('Updated document count:', updateResult.modifiedCount);
// 删除文档
const deleteResult = await collection.deleteOne(query);
console.log('Deleted document count:', deleteResult.deletedCount);
} finally {
await client.close(); // 关闭连接
}
}
main().catch(console.error);本题详细解读
1. 安装 MongoDB 驱动程序
首先,你需要安装 MongoDB 的 Node.js 驱动程序:
npm install mongodb
2. 连接到 MongoDB
使用 MongoClient 类来连接到 MongoDB 数据库。你需要提供一个连接字符串(URI),通常包括主机名、端口号和数据库名称。
const uri = 'mongodb://localhost:27017'; const client = new MongoClient(uri); await client.connect();
3. 选择数据库和集合
连接成功后,你可以选择要操作的数据库和集合:
const database = client.db('mydatabase');
const collection = database.collection('mycollection');4. 插入文档
使用 insertOne 或 insertMany 方法插入文档:
const insertResult = await collection.insertOne({ name: 'John', age: 30 });5. 查询文档
使用 findOne 或 find 方法查询文档:
const findResult = await collection.findOne({ name: 'John' });6. 更新文档
使用 updateOne 或 updateMany 方法更新文档:
const updateResult = await collection.updateOne({ name: 'John' }, { $set: { age: 31 } });7. 删除文档
使用 deleteOne 或 deleteMany 方法删除文档:
const deleteResult = await collection.deleteOne({ name: 'John' });8. 关闭连接
操作完成后,记得关闭数据库连接以释放资源:
await client.close();
通过以上步骤,你可以在 Node.js 中轻松地操作 MongoDB 数据库。