mongodb 使用笔记

# linux 下安装 mongodb

下载二进制文件后,终端输入:

# 不使用配制文件启动
./bin/mongod -auth --dbpath=/data/mongodb/data --logpath=/data/mongodb/logs --logappend --port=27017 --fork
1
2

# 补充

官方提供 deb 等二进制包,可以使用。

# 修改配制文件

修改 /etc/mongod.conf

# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /home/junlsoft/mongodb/data
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /home/junlsoft/mongodb/logs

# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0


# how the process runs
processManagement:
  timeZoneInfo: /usr/share/zoneinfo
  fork: true

security:
  authorization: enabled

#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options:

#auditLog:

#snmp:
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

# 使用配置文件启动

mongod --config /etc/mongod.conf
1

# GUI 工具推荐

  1. robo3t(轻量,免费)
  2. 3t studio(重量,收费)
  3. dbKoda(重量,免费)

# 备份与恢复

利用 bin 下的 mongodump 和 mongorestore

# 备份

[[email protected] bin]# ./mongodump -d my_mongodb
connected to: 127.0.0.1
DATABASE: my_mongodb     to     dump/my_mongodb
my_mongodb.system.indexes to dump/my_mongodb/system.indexes.bson
1 objects
my_mongodb.user to dump/my_mongodb/user.bson
2 objects
[[email protected] bin]# ll
总计 67648
-rwxr-xr-x 1 root root 7508756 2011-04-06 bsondump
drwxr-xr-x 3 root root    4096 04-10 23:54 dump
-rwxr-xr-x 1 root root 2978016 2011-04-06 mongo
1
2
3
4
5
6
7
8
9
10
11
12

# 恢复

[[email protected] bin]# ./mongorestore -d my_mongodb my_mongodb_dump/
connected to: 127.0.0.1
Wed Apr 11 00:03:03 my_mongodb_dump/my_mongodb/user.bson
Wed Apr 11 00:03:03      going into namespace [my_mongodb.user]
Wed Apr 11 00:03:03      2 objects found
Wed Apr 11 00:03:03 my_mongodb_dump/my_mongodb/system.indexes.bson
Wed Apr 11 00:03:03      going into namespace [my_mongodb.system.indexes]
Wed Apr 11 00:03:03 { name: "_id_", ns: "my_mongodb.user", key: { _id: 1 }, v: 0 }
Wed Apr 11 00:03:03      1 objects found
[[email protected] bin]#
1
2
3
4
5
6
7
8
9
10

# 新建用户无法授权登录

千万不要相信 robo3t 自带的权限可视化操作,这是元凶。 千万不要相信 robo3t 自带的权限可视化操作,这是元凶。 千万不要相信 robo3t 自带的权限可视化操作,这是元凶。

根本原因是 mongodb 加入了 SCRAM-SHA-1 校验方式

删除原来的用户后用 shell 创建:

db.createUser({ user: "admin", pwd: "admin", roles: ["root"] });
1

登录 shell 可以用:

mongo admin -u root -p 123456
1

# 复杂查询和数据聚合

普通查询这里不做阐述,看看文档很容易理解。这里主要讲一些高级查询。

# 用 $lookup 进行联合查询

例如

// member
{
  "_id": ObjectId("5b803abf3beda646c35c0504"),
  "name": "测试用户",
  "role": "admin",
  "sex": "男",
  "password": "0"
}
1
2
3
4
5
6
7
8
// project
{
    "projectName": "AAA",
    "createDate": "2018-08-25"
    "memberId": ObjectId("5b803abf3beda646c35c0504")
}
1
2
3
4
5
6

如果要查询 project 的时候带出 member 的数据

db.getCollection("project").aggregate([
  {
    $match: { projectName: projectName },
  },
  {
    $lookup: {
      from: "member",
      localField: "memberId",
      foreignField: "_id",
      as: "memberDetail",
    },
  },
]);
1
2
3
4
5
6
7
8
9
10
11
12
13

# 用 $sort 进行排序

db.getCollection('project').aggregate([
    {
        $match: { "projectName": projectName }
    },
    {
      $lookup: {
        from: "member",
        localField: "memberId",
        foreignField: "_id",
        as: "memberDetail"
      }
    }{
      $sort: { createDate: -1 }
    }
])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 用 $limit 进行限制条数

db.getCollection('project').aggregate([
    {
        $match: { "projectName": projectName }
    },
    {
      $lookup: {
        from: "member",
        localField: "memberId",
        foreignField: "_id",
        as: "memberDetail"
      }
    }{
      $sort: { createDate: -1 }
    },
    {
      $limit: 10
    }
])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

注: $limit 可以与 $skip 配合,达到分页查询的效果。

# 用 $unwind 扁平化数据

({
  "_id": ObjectId("5b803b0a3beda646c35c050b"),
  "projectName": "测试项目",
  "startTime": 0,
  "endTime": 0,
  "desc": "描述",
  "members": [ObjectId("5b803abf3beda646c35c0504"), ObjectId("5b803ef73beda646c35c05a6")]
},
{
  "_id": ObjectId("5b8041043beda646c35c0609"),
  "projectName": "测试项目2",
  "startTime": 0,
  "endTime": 0,
  "desc": "描述",
  "members": [ObjectId("5b803ef73beda646c35c05a6")]
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

扁平化处理:

db.getCollection("project").aggregate([
  {
    $unwind: "$members",
  },
]);
1
2
3
4
5

输出结果:

({
  "_id": ObjectId("5b803b0a3beda646c35c050b"),
  "projectName": "测试项目",
  "startTime": 0,
  "endTime": 0,
  "desc": "描述",
  "members": ObjectId("5b803abf3beda646c35c0504")
},
{
  "_id": ObjectId("5b803b0a3beda646c35c050b"),
  "projectName": "测试项目",
  "startTime": 0,
  "endTime": 0,
  "desc": "描述",
  "members": ObjectId("5b803ef73beda646c35c05a6")
},
{
  "_id": ObjectId("5b8041043beda646c35c0609"),
  "projectName": "测试项目2",
  "startTime": 0,
  "endTime": 0,
  "desc": "描述",
  "members": ObjectId("5b803ef73beda646c35c05a6")
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 复杂数据插入

# 插入到子集合

例如如下结构:

// project
{
  "projectName": "AAA",
  "createDate": "2018-08-25",
  "tags": ["tag1", "tag2"]
}
1
2
3
4
5
6

如果要插入一个 "tag3" 操作方式如下:

project.update(
  { projectName: "AAA" },
  {
    $addToSet: {
      tags: "tag3",
    },
  },
);
1
2
3
4
5
6
7
8

结果:

// project
{
  "projectName": "AAA",
  "createDate": "2018-08-25",
  "tags": ["tag1", "tag2", "tag3"]
}
1
2
3
4
5
6

# 插入到子集合的子集合

例如如下结构:

// project
{
  "projectName": "AAA",
  "createDate": "2018-08-25",
  "children": [
    {
      "name": "BBB",
      "children": ["A", "B"]
    }
  ]
}
1
2
3
4
5
6
7
8
9
10
11

如果要插入一个 "C" 操作方式如下:

project.update(
  { "children.name": "BBB" },
  {
    $addToSet: {
      "children.$.children": "C",
    },
  },
);
1
2
3
4
5
6
7
8

结果:

// project
{
  "projectName": "AAA",
  "createDate": "2018-08-25",
  "children": [
    {
      "name": "BBB",
      "children": ["A", "B", "C"]
    }
  ]
}
1
2
3
4
5
6
7
8
9
10
11