1 概念
2
3 RDBMS(关系型数据库管理系统) MongoDB
4 Database(数据库) Database(数据库)
5 Table(表) Collection(集合)
6 Record(记录) Document(文档)
7
8
9
10 库级操作
11
12 use DATABASE #切换/创建库
13 show dbs #查看所有数据库(空库不会显示)
14 db.dropDatabase() #删除当前数据库
15 db #查看当前所在库
16
17
18
19 集合操作
20
21 db.createCollection(name, options) #创建集合 用引号引起来
22 capped:类型为boolean,如果为true则为创建一个固定大小的集合,当集合中的数据条目达 到最大时自动覆盖以前的条目。
23 size:指定集合字节最大值,当capped为true时需要指定。单位为byte
24 max:指定集合中数据的最大条数。
25 db.createCollection(
26 "BizUser",
27 {capped:1,autoIndexID:1,size:6142800,max:10000}
28 )
29
30 show collections #查看当前数据库的集合
31
32 db.集合名称.drop() #删除集合
33
34
35
36 文档操作
37
38 插入
39
40 db.集合名称.insert(document) #插入文档, 集合不存在会自动创建, 不能插入重复id的数据
41
42 db.student.insert({_id:1, name:'句号', age:18})
43
44
45 db.student.insert([
46 {name:'juhao', sex:'男', age:18},
47 {name:'nanbei', sex:'男', age:19},
48 {name:'budong', sex:'男', age:20},
49 ])
50
51 查询
52
53 db.集合名称.find() #查询所有
54 db.集合名称.find().pretty() #结构化显示
55
56 db.集合.find({name:10}).pretty() where name = 10
57 db.集合.find({name:{$ne:10} }).pretty() where name != 10
58 db.集合.find({name:{$gt:10} }).pretty() where name > 10
59 db.集合.find({name:{$lt:10} }).pretty() where name < 10
60 #后面加个e就是加等于
61
62
63
64 #and逻辑
65 {$and:[{expression1}, {expression1}, ...] }
66 #or逻辑
67 {$or:[{expression1}, {expression1}, ...] }
68
69
70 #where sex='男' and age > 18
71 db.table.find({
72 $and:[
73 {sex:'男'}, {age:{$gt:18}}
74 ]
75 })
76
77
78 #where sex='女' or age =18
79 db.table.find({
80 $or:[
81 {sex:'女'}, {age:18}
82 ]
83 })
84
85
86 #where (sex='女' and age=18) or (sex='男' and age>18)
87 db.table.find({
88 $or:[
89 {$and:[{sex:'女'}, {age:18}]},
90 {$and:[{sex:'男'}, {age:{$gt:18}}]}
91 ]
92 })
93
94
95
96 更新
97
98 db.table.update({sex:'男'},[{age:20}) #更新第一条找到的文档全部值 无multi
99
100 db.table.update({sex:'男'}, {$set:{age:666, agee:6666}}) #修改第一条找到的文档,不存在就添加
101
102 db.table.update({sex:'男'}, {$set:{sex:'女'}}, {multi:true}) #更新全部
103
104
105
106 删除
107
108 db.集合名称.remove( <query>, <justOne> )
109 db.table.remove({age:18}) #删除所有满足条件的
110 db.table.remove({sex:'男'}, {justOne:true}) #删除一条
111
112
113
114 mongodb配置
115
116 vim /etc/mongodb.conf
117 dbpath #数据存放的地址
118 logpath #日志存放的地址
119 bind_ip = 0.0.0.0 #监听IP
120 auth = True #权限认证
121
122
123
124 mongodb权限
125
126 MongoDB默认设置为无权限访问限制
127
128 #进入user admin
129
130 #创建管理员用户,用来管理用户,可以通过这个角色来创建、删除用户,用户只具有管理用户和角色的权限。
131 db.createUser({
132 user:'juha',
133 pwd:'123456',
134 roles:[{role:"userAdminAnyDatabase", db:"admin"}]
135 })
136 #role:指定用户的角色,db指定库
137
138
139 db.createCollection('student') #创建一个库
140 use student #进入
141
142 #给该库添加用户
143 db.createUser({
144 user:'test',
145 pwd:'test',
146 roles:[{
147 role:'readWrite',
148 db:'student'
149 }]
150 })
151
152
153 show users #查看当前库下的用户
154 db.dropUser('username') #删除某个用户
155 db.dropAllusers() #删除当前库的所有用户
156 db.getUsers() #查询所有用户
157