Node.js使用mongodb.js操作MongoDB数据库
2023-09-14 09:07:16 时间
文档:
- npmjs https://npmjs.com/package/mongodb
- documentation https://docs.mongodb.com/drivers/node
安装
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 }
// ]
// 关闭连接
await client.close();
}
func()
相关文章
- js里slice,substr和substring的区别
- [Debug] Debug Node.js Application by using Chrome Dev tools
- Cocos2d-js中Chipmunk引擎
- [Node.js] mongoose schema
- [Docker] Linking Node.js and MongoDB Containers
- js中高效拼接字符串
- sap-ui-core.js reference in Webclient ui
- 如何使用 multiparty 工具库在 Node.js 应用里解析 multipart form-data 格式的请求
- MongoDB 入门教程系列之一:开发环境搭建以及 Node.js 和 Java 的读写访问
- 华为OD机试 - 数字加减游戏(Java & JS & Python)
- node.js mongodb ReplSet
- Node.js学习笔记(四)——NodeJS访问MongoDB与MySQL数据库
- bootstarp modal自己主动调整宽度的JS代码
- js-template-art【三】js api
- 华为校招机试 - 发广播(Java & JS & Python)
- Node.js stream模块(一)可读流
- 使用JS获取当前页面的URL(网址信息)
- 慕课网前端项目:Vue2.0+Node.js+MongoDB全栈打造商城系统 笔记 整理【6/18】