查看有哪些数据库
show dbs
创建或进入数据库 (当数据库不存在即创建)
use dbName
查看有哪些集合
show collections
2、创建集合 / 向集合中插入文档
可以直接向集合插入数据,对不存在的集合将会创建
db.collName.insert({“name”:“Axton”, “age”:20})
3、显示集合中的文档
显示集合中全部文档
db.collName.find()
显示集合中特定文档
db.collName.find({ “name”:“Axton” })
排序,按 ID 倒序排序
db.collName.find().sort({_id:-1})
4、更新文档
db.collName.update({“name”:“Axton”, $set:{“name”: “Axton2”}})
5、删除文档
db.collName.remove({“name”: “Axton”})
六、Node.js 中使用 mongodb 插件连接数据库
1、初始化环境
初始化 node.js 环境
npm init -y
安装 mongodb 模块
npm i mongodb --save
2、连接到 Mongodb
const MongoClient = require(‘mongodb’).MongoClient
const url = ‘mongodb://localhost:27017’ // 默认端口号为 27017 ,如修改过请自行更改
const dbName = ‘mydb’ // 需要连接的数据库名字
MongoClient.connect(
url,
{
// 配置 (默认写上就好)
useUnifiedTopology: true
},
(err, client) => {
if (err) {
console.error(‘mongodn connect error’, err)
return
}
console.log(‘mongodb connect success’)
// 切换到数据库
const db = client.db(dbName)
// 关闭连接
client.close()
}
)
3、文档(Document)的操作
查询文档
const MongoClient = require(‘mongodb’).MongoClient
const url = ‘mongodb://localhost:27017’
const dbName = ‘mydb’
MongoClient.connect(
url,
{
useUnifiedTopology: true
},
(err, client) => {
if (err) {
console.error(‘mongodn connect error’, err)
return
}
console.log(‘mongodb connect success’)
const db = client.db(dbName)
// 使用集合
const usersCollection = db.collection(‘students’)
// ------- 文档的操作代码写在此部分,之后将不再包含连接部分代码 -------
// 查询文档
usersCollection.find({ // find() 内不写内容则为查询全部文档
“name” : “Axton”
}).toArray((err, res) => {
if (err) {
console.error(err)
return
}
console.log(res)
// find() 为异步操作,为了使查询完后在关闭数据,所以放至此位置
client.close()
})
// -------------------------------------------------------------
}
)
插入文档
// 插入一条数据, 插入多条可以选择 insertMany()
usersCollection.insertOne({
name: ‘Jack’,
sex: ‘男’,
age: 21
}, (err, res) => {
if (err) {
console.error(err)
return
}
console.log(res)
client.close()
})
更新文档
// 更新一条数据, 更新多条可以选择 updateMany()
usersCollection.updateOne(
{name: ‘Jack’}, // 查询条件
{$set: {info: ‘女装’}}, // 更新的内容
(err, res) => {
if (err) {
console.error(err)
return
}
console.log(res)
client.close()
}
)
删除文档
// 删除一条数据, 删除多条可以选择 deleteMany()
usersCollection.deleteOne({
name: ‘Jack’
}, (err, res) => {
if (err) {
console.error(err)
return
}
console.log(res)
client.close()
})
4、说明
mongodb 是偏底层一点的插件,此处学习使用此插件是为了让大家了解连接 mongodb 的一些原理。在日常中,为了利于项目开发,通常使用 mongoose 插件
七、Node.js 中使用 mongoose 插件连接数据库
1、说明
由于 mongodb 的数据格式过于灵活,容易导致多人开发时数据格式出错,使用 mongoose 可以更加规范的使用数据.
重要名词和操作
- Schema 定义数据格式的规范
- 以 Model 规范 Collection
- 规范数据操作的 API
2、初始化环境
安装 mongoose 插件
npm i m 《大厂前端面试题解析+Web核心总结学习笔记+企业项目实战源码+最新高清讲解视频》无偿开源 徽信搜索公众号【编程进阶路】 ongoose --save
目录结构
mongoose-test
├── package-lock.json
├── package.json
├── node_modules
└── src
├── db.js
├── models
│ └── Student.js
└── test
└── student.js
3、创建连接服务
db.js
const mongoose = require(‘mongoose’)
const url = ‘mongodb://localhost:27017’
const dbName = ‘myblog’
mongoose.connect(${url}/${dbName}
, {
useUnifiedTopology: true,
useNewUrlParser: true
})
const db = mongoose.connection // 将连接对象赋给 db
// 发送错误
db.on(‘error’, err => {
console.error(err)
})
// 连接成功
db.on(‘open’, () => {
console.log(‘success!’)
})
module.exports = mongoose
4、定义 Schema 规范和创建模型
models/Students.js
// 对应 students 集合
const mongoose = require(‘…/db’)
// 用 Schema 定义数据规范
const StudentSchema = mongoose.Schema({
name: {
type: String,
required: true,
unique: true
},
sex: String,
age: Number
}, {
timestamps: true // 时间戳, 在插入、更新数据后将会加上相应的时间数据