发布于 

mongodb + mongoose

MongoDB

命令行

新版mongoDB的bin文件中没有sh工具,需要手动下载mongosh

  • mongo shell 基础操作
  • MongoDB 菜鸟教程
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    # 进入mongo命令行:
    mongosh

    # 查看所有数据库
    show dbs

    # 切换到指定数据库(创建数据库)
    use dbName

    # 删除数据库
    db.dropDatabase()

    #显示所有集合
    show collections

    # 新增集合
    db.createCollection(name,option)

    # 集合重命名
    db.adminCommand({
    renameCollection: "sourceDb.sourceCollection",
    to: "targetDb.targetCollection",
    dropTarget: <boolean>
    })

    #查询集合所有数据
    db.collectionName.find()

    #新增一条数据
    db.users.insertOne({"name":"admin","age":24,"status":1})

    #删除一条数据
    db.users.deleteOne({})

    #删除指定表
    db.collectionName.drop()

    #清空指定表数据
    db.collectionName.remove({})

    #创建索引
    db.collectionName.ensureIndex({"useranme":1})

    #获取集合索引
    db.user.getIndexes()

    #管道查询
    db.user.aggregate(
    [
    {
    $lookup: {
    from: "news",
    localField: "sn",
    foreignField: "authorSn",
    as: "workList"
    }
    }
    ]
    )
备份、还原、导入、导出

数据库导入、导出操作前,确保数据库打开

1
2
3
4
5
# 数据库导出
mongodump -h dbhost -d dbname -o dbdirectory

# 数据库导入
mongorestore -h dbhost -d dbname <path>

Mongoose

基本操作步骤

步骤1:引入mongoose

1
npm i --save mongoose
1
const mongoose = require('mongoose')

步骤2:建立连接

1
mongoose.connect('mongodb://127.0.0.1:27017/test')

步骤3:定义Schema表模版:

1
2
3
4
5
const UserSchema = mongoose.Schema({
name:String,
age:Number,
status:Number
})

步骤4:定义数据库模型:

1
2
3
4
// model第一个参数,首字母需要大写
// mongoDB中数据库命名,单数和复数之间会默认产生联系 user-users
// 也可以通过指定第三个参数建立联系
const User = mongoose.model('User',UserSchema,'user')

步骤5:操作

操作文档

  • 增 save
  • 删 deleteOne
  • 改 updateOne
  • 查 find

Schema

管道查询

aggregate
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
UserModel.aggregate([
{
$lookup:{
from:'news',
localField:'sn',
foreignField:'authorSn',
as:'workList'
}
},
{ // 筛选
$match:{'name':'root'}
}
]).then(res=>{
console.log('关联成功')
console.log(res)
}).catch(err=>{
console.log('关联失败')
console.log(err)
})


多管道查询
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
AricleModel.aggregate([
{ //拉取分类信息
$lookup:{
from:'articlecate', // 目标表
localField:"cid", // 本表字段
foreignField:"_id", // 外表字段
as:"cate", // 转换字段
}
},
{ // 拉取作者信息
$lookup:{
from:'user',
localField:"author_id",
foreignField:"_id",
as:"author",
}
}
])