Node.js使用mongodb操作MongoDB数据库
  TEZNKK3IfmPf 2023年11月13日 17 0

安装

npm i mongodb

文档给出的示例是通过回调函数操作的

这里给出async/await 操作方式,写起来会舒服很多

代码实例

const { MongoClient, ObjectId } = require('mongodb')

// 配置连接参数
const url = "mongodb://localhost:27017";
const options = { useNewUrlParser: true, useUnifiedTopology: true }


async function func() {
// 连接数据库
const client = await MongoClient.connect(url, options)

// 获取库、集合
const data = client.db("data");
const student = data.collection("student")

/**
* 写操作
*/
// 插入数据 insertOne insertMany
const result1 = await student.insertOne(
{ 'name': "Tom", age: 23 }
)
console.log(result1.insertedId);
// 5e8afa00e473da5ac1c0a9b7

// 更新数据 updateOne updateMany
const result2 = await student.updateOne(
{ _id: ObjectId('5e8af9dbda2c0b5aacb9ff1c') },
{ $set: { name: "Jack" } }
)
console.log(result2.modifiedCount); // 1

// 删除数据 deleteOne deleteMany
const result3 = await student.deleteOne(
{ _id: ObjectId('5e8af9dbda2c0b5aacb9ff1c') }
)
console.log(result3.deletedCount); // 1

/**
* 读操作
*/
// 查询数据 findOne find
const result4 = await student.findOne(
{ 'name': "Tom" }
)
console.log(result4);
// { _id: 5e8af9e8007ee05aad2b641f, name: 'Tom', age: 23 }

// 排序:升序(1) 降序(-1), 分页
const result5 = await student.find(
{ 'name': "Tom" }
).skip(2).limit(2).sort({ age: -1 }).toArray()
console.log(result5);
// [
// { _id: 5e8afa00e473da5ac1c0a9b7, name: 'Tom', age: 23 },
// { _id: 5e8afaab247c7c5b0530143e, name: 'Tom', age: 23 }
// ]

// 关闭连接
client.close()
}


func()

 

参考
Node.js 连接 MongoDB

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月13日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月31日   26   0   0 sqlite数据库
  TEZNKK3IfmPf   2024年05月31日   31   0   0 数据库mysql
  TEZNKK3IfmPf   2024年05月31日   27   0   0 数据库mysql
TEZNKK3IfmPf