8.使用Node.js操作MongoDB

书诚小驿2024/12/18前端知识库NodeJSMongoDB

前言

通过 MongoDB 的官方 Node.js 驱动程序来实现。这个驱动程序提供了一个简单而强大的接口,用于连接和操作 MongoDB 数据库。

一、Node.js 连接 MongoDB 数据库

  1. 新建一个 mongodb-test 文件夹,vscode 打开

  2. 打开终端,安装 MongoDB 驱动程序

npm install mongodb
  1. 新建index.js,连接 MongoDB 数据库
const { MongoClient } = require("mongodb");
// 连接到本地运行的 MongoDB 服务,端口为 27017
const client = new MongoClient("mongodb://localhost:27017");
const main = async () => {
  await client.connect();
  // 选择名为 "xxx" 的数据库,如果数据库不存在,则会创建一个新的数据库
  const db = client.db("xxx");
  // 从数据库中选择名为 "cc" 的集合,如果集合不存在,则会创建一个新的集合
  const cc = db.collection("cc");
  // 执行 find() 方法查询集合中的所有文档
  var d = await cc.find();
  // 将游标转换为数组,以便可以方便地处理和查看所有文档
  console.log(await d.toArray());
};
main().finally(() => client.close());
  1. 保存,运行
node index.js

image.png

二、增删改查操作

// index.js
const { MongoClient } = require("mongodb");
const client = new MongoClient("mongodb://localhost:27017");

const clientFun = async function (c) {
  await client.connect();
  const db = client.db("xxx");
  return db.collection("cc");
};
// 在main方法里修改
const main = async () => {};
main().finally(() => client.close());

1、新增

  1. 插入一条数据insertOne
const main = async () => {
  var cc = await clientFun("cc");
  var d = await cc.insertOne({ z: 1 });
  console.log(d);
};
node index.js

image.png

  1. 添加多条数据insertMany
const main = async () => {
  var cc = await clientFun("cc");
  var d = await cc.insertMany([
    { x: 1, y: 2, z: 3 },
    { x: 1, y: 2, z: 3 },
    { x: 1, y: 2, z: 3 },
  ]);
  console.log(d);
};
node index.js

image.png

2、查询

  1. 查询单条数据findOne
const main = async () => {
  var cc = await clientFun("cc");
  var d = await cc.findOne({ z: 1 });
  console.log(d);
};
node index.js

image.png

  1. 查询多条数据find,注意返回的是游标需要toArray()转换
const main = async () => {
  var cc = await clientFun("cc");
  var d = await cc.find({ x: 1 });
  console.log(await d.toArray());
};
node index.js

image.png

3、更新

  1. 更新一条数据updateOne
const main = async () => {
  var cc = await clientFun("cc");
  // update方法第一个参数是查询过滤器,第二个参数是更新操作
  var d = await cc.updateOne({ x: 1 }, { $set: { x: 4 } });
  console.log(d);
};
node index.js

image.png

  1. 更新多条数据updateMany
const main = async () => {
  var cc = await clientFun("cc");
  var d = await cc.updateMany({ x: 4 }, { $set: { x: 3 } });
  console.log(d);
};
node index.js

image.png

4、删除

  1. 删除单条数据deleteOne
const main = async () => {
  var cc = await clientFun("cc");
  var d = await cc.deleteOne({ x: 3 });
  console.log(d);
};
node index.js

image.png

  1. 删除多条数据deleteMany
const main = async () => {
  var cc = await clientFun("cc");
  var d = await cc.deleteMany({ x: 3 });
  console.log(d);
};
node index.js

image.png

最后更新时间' 2025/1/3 14:16:58