教程 mongodb tutorial

Node.js 原生驱动

MongoDB 官方提供的 Node.js 原生驱动,允许在 Node.js 应用中高效操作 MongoDB 数据库。

安装

使用 npm 安装 MongoDB 驱动:

bash
npm install mongodb

`

连接数据库

示例代码连接本地 MongoDB:

js
const { MongoClient } = require('mongodb');

const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

async function run() {
  try {
    await client.connect();
    console.log('Connected to MongoDB');
    const db = client.db('myDatabase');
    // 在此进行数据库操作
  } finally {
    await client.close();
  }
}

run().catch(console.dir);

基本操作示例

插入文档

js
const collection = db.collection('users');
await collection.insertOne({ name: 'Alice', age: 25 });

查询文档

js
const user = await collection.findOne({ name: 'Alice' });
console.log(user);

更新文档

js
await collection.updateOne({ name: 'Alice' }, { $set: { age: 26 } });

删除文档

js
await collection.deleteOne({ name: 'Alice' });

常用配置

  • 支持连接池管理、自动重连。
  • 支持 Promise 和回调两种异步方式。
  • 支持事务操作(需副本集)。

通过 Node.js 原生驱动,开发者可以方便地集成 MongoDB,实现灵活的数据操作和高性能应用。