Node.js——操作MongoDB

操作MongoDB

1、MongoDB概述

由于MongoDB数据库在JavaScript脚本环境中支持BSON对象(JSON对象的二进制形式)的存取,因此对于数据的存取的效率是非常高的。在MongoDB数据库中,将每一条等待插入的数据记录存储在内存中,因此,该数据库是一种非阻塞型数据库,在需要记载大量日志数据、实时测量数据或实时统计数据时,该数据库可以达到令人满意的效果。由于MongoDB数据库支持在查询语句内部使用JavaScript函数,也大大加强了它读取数据的能力。

MongoDB数据库中支持的数据类型:

数据类型 说明 数据使用示例
Array 数组 cardsInHand:[9,4,3]
Boolean 布尔类型,只允许true或false值 hasBeenRead:false
Code 数据库内部可运行的一段JavaScript脚本代码 new BSON.Code( 'function quotient(dividend, divisor){ return divisor == 0 ? 0:dividen / divisor;}');
Date 当前日期和时间 lastUpdated:new Date()
DBRef 数据库引用 bestFriendId: new BSON.DBRef('users', friendObjectId)
Integer 整数值 pageViews:50
Long 长整数值 starsInUniverse=new BSON.Long("100000000000000000");
Hash 一个"键值/键名"形式的数据字典 userName:{'first':'Sam', 'last':'Smith'}
Null null值 bestFriend: null
ObjectID MongoDB数据库中用于索引对象的一个12字节的代码,其表现形式为一个24位的十六进制字符串
String 字符串 fullName: 'Sam Smith'

2、安装MongoDB数据库

可以在MongoDB官网(网址为http://www.mongodb.org/)上根据操作系统类型下载相应的MongoDB数据库安装包。在下载及解压缩后的安装包的bin文件夹中,包含了一系列可执行文件。其中用于运行数据库服务器的可执行文件名为mongod,用于运行与数据库服务器相连接的客户端的可执行文件名为mongo。

在运行数据库服务器之前,需要挑选磁盘中一个空的文件夹,在数据库服务器运行时将会在其中写入一些运行数据库服务器时所需使用的文件。

js 复制代码
mongod -dbpath <用户挑选的磁盘文件夹名>

3、安装MongoDB包

当用户需要在Node.js应用程序中执行MongoDB数据库连接时,可以下载MongoDB包,在下载的包中包含了MongoDB本地驱动程序。可以使用如下所示的命令安装MongoDB包。

shell 复制代码
npm install mongodb

在安装了MongoDB包后,可以使用如下所示的表达式来使用MongoDB模块。

js 复制代码
const { MongoClient } = require("mongodb");

Node.js >= 16

MongoDB >= 4.x

4、连接MongoDB

js 复制代码
const { MongoClient } = require("mongodb");

const uri = "mongodb://localhost:27017"; // 本地
// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/

async function main() {
  const client = new MongoClient(uri);

  try {
    await client.connect();
    console.log("连接成功");

    const db = client.db("testdb");
    const collection = db.collection("users");

    // 这里写你的操作
  } finally {
    await client.close();
  }
}

main().catch(console.error);
js 复制代码
连接成功

3、插入数据

插入单条:

js 复制代码
const { MongoClient } = require("mongodb");

const uri = "mongodb://localhost:27017"; // 本地
// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/

async function main() {
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const db = client.db("testdb");
    const collection = db.collection("users");

    //插入单条数据
    const result = await collection.insertOne({
        name: "张三",
        age: 25,
        email: "123@123.com"
    });

    console.log(result);
    
  } finally {
    await client.close();
  }
}

main().catch(console.error);
js 复制代码
{
  acknowledged: true,
  insertedId: new ObjectId('69d1e8f5add3ecc5377bc361')
}

插入多条:

js 复制代码
const { MongoClient } = require("mongodb");

const uri = "mongodb://localhost:27017"; // 本地
// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/

async function main() {
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const db = client.db("testdb");
    const collection = db.collection("users");

    //插入多条数据
    const result = await collection.insertMany([
        { name: "李四", age: 30 },
        { name: "王五", age: 28 }
    ]);

    console.log(result);
    
  } finally {
    await client.close();
  }
}

main().catch(console.error);
js 复制代码
{
  acknowledged: true,
  insertedCount: 2,
  insertedIds: {
    '0': new ObjectId('69d1e93ef05ee234c2511e27'),
    '1': new ObjectId('69d1e93ef05ee234c2511e28')
  }
}

5、更新数据

更新单条:

js 复制代码
const { MongoClient } = require("mongodb");

const uri = "mongodb://localhost:27017"; // 本地
// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/

async function main() {
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const db = client.db("testdb");
    const collection = db.collection("users");

    //更新单条数据
    const result = await collection.updateOne(
        {name: "张三"},
        {$set: {age: 260}}
    );

    console.log(result);
    
  } finally {
    await client.close();
  }
}

main().catch(console.error);
json 复制代码
{
  acknowledged: true,
  modifiedCount: 1,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 1
}

更新多条:

js 复制代码
const { MongoClient } = require("mongodb");

const uri = "mongodb://localhost:27017"; // 本地
// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/

async function main() {
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const db = client.db("testdb");
    const collection = db.collection("users");

    //更新多条数据
    const result = await collection.updateMany(
        {age: {$lt: 30}},
        {$inc: {age: 1}}
    );

    console.log(result);
    
  } finally {
    await client.close();
  }
}

main().catch(console.error);
json 复制代码
{
  acknowledged: true,
  modifiedCount: 2,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 2
}

6、查询数据

查询所有:

js 复制代码
const { MongoClient } = require("mongodb");

const uri = "mongodb://localhost:27017"; // 本地
// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/

async function main() {
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const db = client.db("testdb");
    const collection = db.collection("users");

    //查询所有数据
    const result = await collection.find().toArray();

    console.log(result);
    
  } finally {
    await client.close();
  }
}

main().catch(console.error);
json 复制代码
[
  {
    _id: new ObjectId('69d1e8e60a6eabb1203b66d5'),
    name: '张三',
    age: 260,
    email: '123@123.com'
  },
  {
    _id: new ObjectId('69d1e8f5add3ecc5377bc361'),
    name: '张三',
    age: 26,
    email: '123@123.com'
  },
  {
    _id: new ObjectId('69d1e93ef05ee234c2511e27'),
    name: '李四',
    age: 30
  },
  {
    _id: new ObjectId('69d1e93ef05ee234c2511e28'),
    name: '王五',
    age: 29
  }
]

条件查询

js 复制代码
const result = await collection.find({name: "张三"}).toArray();
console.log(result);
json 复制代码
[
  {
    _id: new ObjectId('69d1e8e60a6eabb1203b66d5'),
    name: '张三',
    age: 260,
    email: '123@123.com'
  },
  {
    _id: new ObjectId('69d1e8f5add3ecc5377bc361'),
    name: '张三',
    age: 26,
    email: '123@123.com'
  }
]

高级查询:

js 复制代码
const result = await collection.find(
    {age: {$gt: 25}}
).toArray();
console.log(result);
json 复制代码
[
  {
    _id: new ObjectId('69d1e8e60a6eabb1203b66d5'),
    name: '张三',
    age: 260,
    email: '123@123.com'
  },
  {
    _id: new ObjectId('69d1e8f5add3ecc5377bc361'),
    name: '张三',
    age: 26,
    email: '123@123.com'
  },
  {
    _id: new ObjectId('69d1e93ef05ee234c2511e27'),
    name: '李四',
    age: 30
  },
  {
    _id: new ObjectId('69d1e93ef05ee234c2511e28'),
    name: '王五',
    age: 29
  }
]

7、删除数据

删除单条:

js 复制代码
const { MongoClient } = require("mongodb");

const uri = "mongodb://localhost:27017"; // 本地
// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/

async function main() {
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const db = client.db("testdb");
    const collection = db.collection("users");

    //删除单条数据
    const result = await collection.deleteOne({name: "李四"});
    console.log(result);
    
  } finally {
    await client.close();
  }
}

main().catch(console.error);
json 复制代码
{ acknowledged: true, deletedCount: 1 }

删除多条:

js 复制代码
const result = await collection.deleteMany({age : {$gt: 50}});
console.log(result);
json 复制代码
{ acknowledged: true, deletedCount: 1 }

8、索引操作

创建索引:

js 复制代码
const result = await collection.createIndex({email: 1}, {unique: true});
console.log(result);
复制代码
email_1

查看索引:

js 复制代码
const indexes = await collection.indexes();
console.log(indexes);
js 复制代码
[
  { v: 2, key: { _id: 1 }, name: '_id_' },
  { v: 2, key: { email: 1 }, name: 'email_1', unique: true }
]

9、事务(MongoDb 4.0+)

js 复制代码
const { MongoClient } = require("mongodb");

const uri = "mongodb://localhost:27017"; // 本地
// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/

async function main() {
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const db = client.db("testdb");
    const collection = db.collection("users");

    const session = client.startSession();
    try {
        session.startTransaction();
        await collection.insertOne({ name: "事务测试" }, { session });
        await session.commitTransaction();
    } catch (e) {
        await session.abortTransaction();
    } finally {
        session.endSession();
    }
    
  } finally {
    await client.close();
  }
}

main().catch(console.error);

10、与 Express 结合示例

js 复制代码
app.get("/users", async (req, res) => {
  const users = await collection.find().toArray();
  res.json(users);
});
相关推荐
空空潍2 小时前
Spring AI 实战系列(十):MCP深度集成 —— 工具暴露与跨服务调用
数据库·人工智能·spring
bIo7lyA8v2 小时前
从 ChangeTracker 到 SQL Batch 的性能诊断与优化
数据库·sql·batch
Yiyi_Coding2 小时前
Oracle 、 Mysql、Guass 的 sequence
数据库·mysql·oracle
吴声子夜歌3 小时前
Node.js——dns模块
开发语言·node.js·php
吴声子夜歌3 小时前
Node.js——zlib压缩模块
java·spring·node.js
"Wild dream"3 小时前
NodeJs内置的Npm
前端·npm·node.js
数智化管理手记11 小时前
精益生产中的TPM管理是什么?一文破解设备零故障的密码
服务器·网络·数据库·低代码·制造·源代码管理·精益工程
翊谦11 小时前
Java Agent开发 Milvus 向量数据库安装
java·数据库·milvus