MongoDB 的安装
MongoDB下载地址:www.mongodb.com/try/downloa…
下载安装好以后,启动 MongoDB 服务器:
- 新建一个数据文件目录,比如 C:\data\db
- 执行命令进行启动 (先配环境变量 => 让系统知道有这么个目录)
mongod --dbpath=C:\data\db
# mongod 为 MongoDB 的服务器程序
# 数据文件目录默认为 /data/db
MongoDB 服务器启动后,访问 http://localhost:27017,如果出现这样的结果则表示已经成功:
MongoShell 操作数据库
- mongo Shell 是 MongoDB 官方提供的一个在命令行中用来连接操作 MongoDB 服务的客户端工具
- 使用 mongo Shell 可以对 MongoDB 数据库进行数据的管理
命令演示:
-
show dbs 查看数据库
-
db 查看当前数据库
-
use database 切换数据库
-
show collections 查看集合列表
...
插入数据演示:
db.users.insert({ name: 'Jack', age: 18 })
检索查看数据:
db.users.find()
MongoDB 基础概念
MongoDB中的数据存储结构:
- 数据库 database
- 集合 collection (一个集合存一类数据)
- 文档 document (集合中的一项)
- 数据字段 field
MongoDB是文档型数据库, 存储的都是一些 JSON 格式数据
{
// 数据库 database
"test1": {
// 集合 collection
"users": [
// 文档 document
{
// 数据字段 field
"id": 1,
"username": "小明",
"password": "123456"
},
{
"id": 2,
"username": "小王",
"password": "123456",
"desc": "不错"
}
// ...
],
"teachers": [
{
"id": 1,
"name": "李老师"
},
{
"id": 2,
"name": "王老师",
}
]
},
// 数据库
"test2": {}
// ...
}
数据库相关
- 查看数据库列表:
show dbs
- 查看当前数据库:
db
- 创建/切换数据库: (数据库只有真正的有了数据才会被创建出来)
use 数据库名
- 删除当前数据库:
db.dropDatabase()
集合相关
- 创建集合: 只需要往集合中插入数据, 集合会自动创建
db.集合名.insert({ name: 'zs', age: 18 })
- 查看集合
show collections
- 删除集合
db.集合名称.drop()
文档相关
- MongoDB 将数据记录存储为 BSON 文档
- BSON(Binary JSON)是 JSON 文档的二进制表示形式,它比 JSON 包含更多的数据类型
- BSON 规范
- 字段名称
_id保留用作主键;它的值在集合中必须是唯一的,不可变的,并且可以是数组以外的任何类型。
> db.users.find()
{ "_id" : ObjectId("619cc474cc1980baa07f2c24"), "name" : "Jack", "age" : 18 }
MongoDB - 增删改查
可视化操作工具:
- MongoDB Compass 官网地址 : www.mongodb.com/zh-cn/produ…
- navicat 官网地址: www.navicat.com.cn/
创建文档 (增)
db.集合名.insertOne({ ... }) 插入一个
db.集合名.insertMany([{ ... }, { ... }]) 插入多个
db.集合名.insert({ ... }) 插入一个或多个
查询文档 (查)
db.集合名.find() 查询所有
db.集合名.find().pretty() 查询并格式化
db.集合名.find(查询条件, { 键: 0/1 }) 0表示排除, 1表示包含
相等条件
db.集合名.find({
键: 值
})
AND 条件
其他查询运算符: docs.mongodb.com/manual/refe…
db.集合名.find({
键: 值,
键: 值,
键: {
$lt: 值
},
键: /\d/
})
OR 条件
db.集合名.find({
$or: [
{ 键: 值 },
{ 键: 值 }
]
})
更新文档 (改)
// 更新第一个满足条件的项
db.集合名.updateOne(查询条件, {
$set: {
键: 值,
键: 值
}
})
// 更新所有满足条件的项
db.集合名.updateMany(查询条件, {
$set: {
键: 值,
键: 值
}
})
删除文档 (删)
db.collection.deleteMany(查询条件)
db.collection.deleteOne(查询条件)
在 Koa 中连接和调用 MongoDB
构建基本架子
- 安装 mongodb 驱动包
mongodb 是官方提供的 Node.js 驱动包,可以连接 MongoDB 服务器,并通过发送命令来实现对 MongoDB 服务器的各种操作。
yarn add mongodb koa @koa/router
- 创建 db 模块, 使用 mongodb 驱动包连接 MongoDB 服务器
// 1. 引入 mongodb 驱动包
const mongodb = require('mongodb')
const MongoClient = mongodb.MongoClient
// 2. 创建 MongoDB 客户端实例
// MongoDB 服务器的连接地址,其中可包含用户名、密码、域名、端口、数据库名等信息
const mongoClient = new MongoClient('mongodb://127.0.0.1:27017')
// 3. 建立连接
mongoClient.connect()
// 4. 连接关联哪个数据库
const db = mongoClient.db('classroom')
module.exports = db
- 创建路由模块
const Router = require('@koa/router')
const router = new Router()
router.get('/', async ctx => {
ctx.body = '这是首页'
})
router.get('/list', async ctx => {
ctx.body = '这是列表'
})
module.exports = router
- 挂载路由
const Koa = require('koa')
const router = require('./router')
const app = new Koa()
app.use(router.routes())
app.listen(8888, () => console.log('服务器启动成功...'))
执行添加操作
const Router = require('@koa/router')
const db = require('./db')
const router = new Router()
router.get('/', async ctx => {
ctx.body = '这是首页'
})
router.get('/list', async ctx => {
ctx.body = '这是列表'
})
router.get('/add', async ctx => {
const collection = db.collection('students')
const info = await collection.insertOne({ name: 'Tom', age: 18 })
console.log(info)
collection.find().forEach(item => {
console.log(item)
})
ctx.body = '操作完成'
})
module.exports = router
在 Koa 中对 MongoDB 数据进行增删改查
掌握从 Koa 代码中对 MongoDB 的数据做增、删、改、查操作
新增数据
向 MongoDB 中的某个 collection 内新增一条或多条数据,可以使用以下方法:
// 新增一条
await collection.insertOne({ name: 'Tom', age: 18 })
// 新增多条
await collection.insertMany([
{ name: 'Jack', age: '28' },
{ name: 'Marray', age: '21' },
])
默认情况下,新增后的每条数据都会自动被添加上一个:类型为 ObjectID、字段名为 _id 的唯一标识。
删除数据
要删除某个 collection 中的指定 _id 数据,可以使用:
const mongodb = require('mongodb')
const ObjectID = mongodb.ObjectID
collection.deleteOne(
// 查询条件
{
_id: ObjectID('....ID的值.....')
}
)
修改数据
如果要对某个 collection 中的某些数据进行更新,可以使用 updateOne 或 updateMany 方法:
await collection.updateOne(
// 查询条件
{
_id: ObjectID('60bc8eb33e941a0a20875e0d')
},
// 更新表达式选项
{
$set: { name: '张三' }
}
)
查询数据
将某些符合查询条件的数据从 collection 中查找出来,可以使用 find 方法:
const users = await collection.find(
// 查询条件
{
// age 字段值 大于 15
age: {
$gt: 15
}
}
)
查询结果为游标类型(Cursor),不能直接用 for 循环等遍历,可以使用它的 forEach 方法遍历,或先将它转为数组:
// 用 forEach 方法遍历
users.forEach(user => {
console.log(user);
})
// 先转为数组后再用 for 循环遍历
const arr = await users.toArray()
for (const item of arr) {
console.log(item)
}
MongoDB配置用户名和密码进行认证登录
查看目前MongoDB中的所有用户
use admin
show users
创建管理员用户
db.createUser({ user: 'root', pwd: '123456', roles: ["root"]})
重新打开cmd,在mongodb路径的bin目录下,执行
mongod --dbpath=C:\data\db --auth (data是安装mongodb创建的数据库文件夹)