MongoDB 入门笔记

前言

最近给博客接入了评论系统,使用Twikoo + MongoDB Atlas + Vercel 进行部署,MongoDB作为数据库。
后面给评论系统设置密码的时候,由于设置的过于简单,便打算重新设置,按官方的描述是需要删除MonogoDB的 config.ADMIN_PASS 配置项, 但是没有给出具体过程,遂去学习了下MongoDB的基本用法。

先贴出删除config.ADMIN_PASS配置项的方法:

1
2
3
mongosh "mongodb+srv://[user]:[password]@cluster0.uhqzyla.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0"  // 连接字符串从MongoDB Atlas获取
use test // 切换到test数据库
db.config.updateOne({}, {$set: {ADMIN_PASS: ""}}) // 更新config集合中的所有文档,将ADMIN_PASS字段的值设为空字符串

然后再到评论区重新设置密码即可。

介绍

MongoDB 是一种非关系型数据库,也称为NoSQL数据库或面向文档的数据库,它通过以 JSON(JavaScript Object Notation)文档的形式存储数据,实现更高的灵活度和可扩展性。MongoDB不需要像关系数据库 MySQL一样预先设定数据结构,即可以存储数据。每个“文档”可以有不同的数据结构。因此它使得开发者能更专注于业务逻辑的开发,而不需要关心数据库的细节。

下面是MongoDB和MySQL的对比:

MongoDB MySQL
数据库(Database) 数据库(Database)
集合(Collection) 表(Table)
文档(Document) 行(Row)
字段(Field) 列(Column)
索引(Index) 索引(Index)
_id 主键(Primary Key)
$lookup join
$group group by

Linux安装MongoDB

参考官方中文文档:https://www.mongodb.com/zh-cn/docs/manual/tutorial/install-mongodb-on-ubuntu/

Winddows和MacOS安装方式同样可以在上面的的官方文档中查看。

Linux安装完成后若无法启动,可尝试执行 sudo chown mongodb:mongodb /tmp/mongodb-27017.sock 再启动。

连接MongoDB

  1. 连接本机MongoDB:

使用默认端口 27017 连接到本机运行的 MongoDB 服务器,需要运行不带任何选项的 MongoDB 官方命令行界面工具 mongo shel

1
mongosh

这也相当于运行以下命令:

1
mongosh "mongodb://localhost:27017"
  1. 连接远程MongoDB:
1
mongosh "mongodb://mongodb0.example.com:28015"

基本用法

命令使用技巧:可以使用上下方向键选择历史命令执行;可以用TAB按键快速补全命令。

1.切换数据库
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
test> help  // 查看帮助

Shell Help:

use Set current database
show 'show databases'/'show dbs': Print a list of all available databases.
'show collections'/'show tables': Print a list of all collections for current database.
'show profile': Prints system.profile information.
'show users': Print a list of all users for current database.
'show roles': Print a list of all roles for current database.
'show log <type>': log for current connection, if type is not set uses 'global'
'show logs': Print all logs.

exit Quit the MongoDB shell with exit/exit()/.exit
quit Quit the MongoDB shell with quit/quit()
Mongo Create a new connection and return the Mongo object. Usage: new Mongo(URI, options [optional])
connect Create a new connection and return the Database object. Usage: connect(URI, username [optional], password [optional])
it result of the last line evaluated; use to further iterate
version Shell version
load Loads and runs a JavaScript file into the current shell environment
enableTelemetry Enables collection of anonymous usage data to improve the mongosh CLI
disableTelemetry Disables collection of anonymous usage data to improve the mongosh CLI
passwordPrompt Prompts the user for a password
sleep Sleep for the specified number of milliseconds
print Prints the contents of an object to the output
printjson Alias for print()
convertShardKeyToHashed Returns the hashed value for the input using the same hashing function as a hashed index.
cls Clears the screen like console.clear()
isInteractive Returns whether the shell will enter or has entered interactive mode

For more information on usage: https://docs.mongodb.com/manual/reference/method

test>
test> cls // 清屏
test>
test> db // 查看当前数据库, 为test
test>
test> show database // 查看所有数据库,发现并没有test数据库,原因是MongoDB默认使用不存在的test数据库,并且MongoDB允许使用不存在的数据库,但只有往里面插入数据时,才会创建数据库
admin 40.00 KiB
config 108.00 KiB
game 72.00 KiB
local 72.00 KiB
test>
test> show dbs // 和上面的命令效果一样
admin 40.00 KiB
config 108.00 KiB
game 72.00 KiB
local 72.00 KiB
test>
local> use local // 切换到已存在的local数据库
switched to db local
local>
game> use game // 切换到不存在的数据库也行(只有往里面插入数据时,才会创建数据库)
switched to db game
game>
2.简单的创建数据库和插入数据以及查询数据
1
2
3
4
5
6
7
8
9
game> db.users.insertOne({name: "lololowe"})  // 在当前数据库中创建一个集合users,并使用insertOne()函数插入一条键值对数据
{
acknowledged: true, // 表示插入成功
insertedId: ObjectId('660d76453ded4220cc7b2da9') // 该字段是MongoDB自动添加的全局唯一ID
}
game>
game> db.users.find() // 查看当前数据库的users集合中的所有文档
[ { _id: ObjectId('660d3988cf82e7e7fc7b2da9'), name: 'lololowe' } ]
game>

从上面的示例中可以看到,我们并没有执行创建数据库或者创建表之类的操作,比如定义表中的每一列的名称,数据类型或者长度等等,而只是插入了一个json对象,剩下的工作都是MongoDB自动完成的,这就是MongoDB的一个特点。
这里的json对象就是MongoDB中的文档,MongoDB中的数据都是以文档的形式来存储的。文档在MongoDB中是一个非常重要的概念 它类似于MySQL或者其他关系型数据库中的一行记录,但是,MongoDB中的文档和MySQL中的行有很多不同的地方, 比如不同的文档之间并不需要有相同的结构和字段,也就是说,文档之间的结构可以不同:

1
2
3
4
5
6
7
8
9
10
11
12
game> db.users.insertOne({name: "张三", age: "18"})  // 该文档多插入了个age字段
{
acknowledged: true,
insertedId: ObjectId('660d7c9b3ded4220cc7b2dad')
}
game>
game> db.users.find()
[
{ _id: ObjectId('660d78af3ded4220cc7b2dac'), name: 'lololowe' },
{ _id: ObjectId('660d7c9b3ded4220cc7b2dad'), name: '张三', age: '18' }
]
game>

也可以使用一条语句来插入多条数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
game> db.users.insertMany([{name: "李四"}, {name: "王五"}])  // 使用insertMany()函数并使用数组作为参数来同时插入2条数据
{
acknowledged: true,
insertedIds: {
'0': ObjectId('660d7e253ded4220cc7b2dae'),
'1': ObjectId('660d7e253ded4220cc7b2daf')
}
}
game>
game> db.users.find()
[
{ _id: ObjectId('660d78af3ded4220cc7b2dac'), name: 'lololowe' },
{ _id: ObjectId('660d7c9b3ded4220cc7b2dad'), name: '张三', age: '18' },
{ _id: ObjectId('660d7e253ded4220cc7b2dae'), name: '李四' },
{ _id: ObjectId('660d7e253ded4220cc7b2daf'), name: '王五' }
]
game>
3.limit()

先插入一些数据,用于后面的测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
game> db.users.insertMany([
{name: "刘备", email: "liubei@qq.com", level: 1, skills: ["谋略", "领导"]},
{name: "关羽", email: "guanyu@qq.com", level: 2, skills: ["武艺", "忠诚"]},
{name: "张飞", email: "zhangfei@qq.com", level: 3, skills: ["力量" ,"勇猛"]},
{name: "赵云", email: "zhaoyun@qq.com", level: 4, skills: ["智勇", "忠诚"]},
{name: "曹操", email: "caocao@qq.com", level: 5, skills: ["智谋", "军事"]},
{name: "孙权", email: "sunquan@qq.com", level: 6, skills: ["勇猛", "智计"]}
])
{
acknowledged: true,
insertedIds: {
'0': ObjectId('661a2f4188cec2c9eeef634b'),
'1': ObjectId('661a2f4188cec2c9eeef634c'),
'2': ObjectId('661a2f4188cec2c9eeef634d'),
'3': ObjectId('661a2f4188cec2c9eeef634e'),
'4': ObjectId('661a2f4188cec2c9eeef634f'),
'5': ObjectId('661a2f4188cec2c9eeef6350')
}
}
game>
1
2
3
game> db.users.find().limit(1)  // 使用limit()函数来限制返回的结果条数(文档数)为1条
[ { _id: ObjectId('660d78af3ded4220cc7b2dac'), name: 'lololowe' } ]
game>
4.sort()
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
game> db.users.find().sort({level: 1})  // 使用sort()函数来对结果进行排序,1表示升序,-1表示降序
[
{ _id: ObjectId('660d78af3ded4220cc7b2dac'), name: 'lololowe' },
{ _id: ObjectId('660d7c9b3ded4220cc7b2dad'), name: '张三', age: '18' },
{ _id: ObjectId('660d7e253ded4220cc7b2dae'), name: '李四' },
{ _id: ObjectId('660d7e253ded4220cc7b2daf'), name: '王五' },
{
_id: ObjectId('661a2f4188cec2c9eeef634b'),
name: '刘备',
email: 'liubei@qq.com',
level: 1,
skills: [ '谋略', '领导' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634c'),
name: '关羽',
email: 'guanyu@qq.com',
level: 2,
skills: [ '武艺', '忠诚' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634d'),
name: '张飞',
email: 'zhangfei@qq.com',
level: 3,
skills: [ '力量', '勇猛' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634e'),
name: '赵云',
email: 'zhaoyun@qq.com',
level: 4,
skills: [ '智勇', '忠诚' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634f'),
name: '曹操',
email: 'caocao@qq.com',
level: 5,
skills: [ '智谋', '军事' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef6350'),
name: '孙权',
email: 'sunquan@qq.com',
level: 6,
skills: [ '勇猛', '智计' ]
}
]
game>
game> db.users.find().sort({level: -1}) // 按等级来降序排序
[
{
_id: ObjectId('661a2f4188cec2c9eeef6350'),
name: '孙权',
email: 'sunquan@qq.com',
level: 6,
skills: [ '勇猛', '智计' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634f'),
name: '曹操',
email: 'caocao@qq.com',
level: 5,
skills: [ '智谋', '军事' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634e'),
name: '赵云',
email: 'zhaoyun@qq.com',
level: 4,
skills: [ '智勇', '忠诚' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634d'),
name: '张飞',
email: 'zhangfei@qq.com',
level: 3,
skills: [ '力量', '勇猛' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634c'),
name: '关羽',
email: 'guanyu@qq.com',
level: 2,
skills: [ '武艺', '忠诚' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634b'),
name: '刘备',
email: 'liubei@qq.com',
level: 1,
skills: [ '谋略', '领导' ]
},
{ _id: ObjectId('660d78af3ded4220cc7b2dac'), name: 'lololowe' },
{ _id: ObjectId('660d7c9b3ded4220cc7b2dad'), name: '张三', age: '18' },
{ _id: ObjectId('660d7e253ded4220cc7b2dae'), name: '李四' },
{ _id: ObjectId('660d7e253ded4220cc7b2daf'), name: '王五' }
]
game>
game> db.users.find().sort({level: -1}).limit(2) // 按等级降序的同时限制只返回2条结果
[
{
_id: ObjectId('661a2f4188cec2c9eeef6350'),
name: '孙权',
email: 'sunquan@qq.com',
level: 6,
skills: [ '勇猛', '智计' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634f'),
name: '曹操',
email: 'caocao@qq.com',
level: 5,
skills: [ '智谋', '军事' ]
}
]
game>
game> db.users.find().sort({level: -1, name: 1}).limit(2) // 在等级相同的时候,会按姓名首字母来升序排序
[
{
_id: ObjectId('661a2f4188cec2c9eeef6350'),
name: '孙权',
email: 'sunquan@qq.com',
level: 6,
skills: [ '勇猛', '智计' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634f'),
name: '曹操',
email: 'caocao@qq.com',
level: 5,
skills: [ '智谋', '军事' ]
}
]
game>
5.skip()
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
game> db.users.find().sort({level: -1}).limit(2)  // 按等级降序排序的同时限制只返回2条结果
[
{
_id: ObjectId('661a2f4188cec2c9eeef6350'),
name: '孙权',
email: 'sunquan@qq.com',
level: 6,
skills: [ '勇猛', '智计' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634f'),
name: '曹操',
email: 'caocao@qq.com',
level: 5,
skills: [ '智谋', '军事' ]
}
]
game>
game> db.users.find().sort({level: -1}).limit(2).skip(1) // 使用skip()函数来跳过第一条结果,从第二条开始返回,但返回结果的总数仍限制为2条。skip()函数和sort()函数组合可实现翻页功能
[
{
_id: ObjectId('661a2f4188cec2c9eeef634f'),
name: '曹操',
email: 'caocao@qq.com',
level: 5,
skills: [ '智谋', '军事' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634e'),
name: '赵云',
email: 'zhaoyun@qq.com',
level: 4,
skills: [ '智勇', '忠诚' ]
}
]
game>
5.find({field: value})

find({field: value})类似于SQL中的WHERE语句

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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
game> db.users.find({level: 3})  // 过滤查找等级为3的用户
[
{
_id: ObjectId('661a2f4188cec2c9eeef634d'),
name: '张飞',
email: 'zhangfei@qq.com',
level: 3,
skills: [ '力量', '勇猛' ]
}
]
game>
game> db.users.find({level: "3"}) // 注意,MongoDB的数字类型是Number,字符串类型是String,等级为字符串三的用户并不存在, 因此不会返回任何的数据
game>
game> db.users.find({level: 3}, {name: 1, email: 1}) // 使用find()函数来过滤查找等级为3的用户,并只返回name和email字段
[
{
_id: ObjectId('661a2f4188cec2c9eeef634d'),
name: '张飞',
email: 'zhangfei@qq.com'
}
]
game>
game> db.users.find({level: 3}, {name: 1, email: 1, _id: 0}) // 设置_id: 0来排除Mongodb自动添加的_id字段
[ { name: '张飞', email: 'zhangfei@qq.com' } ]
game>
game> db.users.find({level: 3}, {email: 0}) // 会返回等级为3的用户的email字段以外的所有字段
[
{
_id: ObjectId('661a2f4188cec2c9eeef634d'),
name: '张飞',
level: 3,
skills: [ '力量', '勇猛' ]
}
]
game>
game> db.users.find({level: {$gt: 5}}) // 使用$gt操作符来查找等级大于5的用户, gt表示大于(greater than)
[
{
_id: ObjectId('661a2f4188cec2c9eeef6350'),
name: '孙权',
email: 'sunquan@qq.com',
level: 6,
skills: [ '勇猛', '智计' ]
}
]
game>
game> db.users.find({level: {$lt: 2}}) // 使用$lt操作符来查找等级小于2的用户, lt表示小于(less than)
[
{
_id: ObjectId('661a2f4188cec2c9eeef634b'),
name: '刘备',
email: 'liubei@qq.com',
level: 1,
skills: [ '谋略', '领导' ]
}
]
game>
game> db.users.find({level: {$eq: 5}}) // 使用$eq操作符来查找等级等于5的用户, eq表示等于(equal)
[
{
_id: ObjectId('661a2f4188cec2c9eeef634f'),
name: '曹操',
email: 'caocao@qq.com',
level: 5,
skills: [ '智谋', '军事' ]
}
]
game>
game> db.users.find({level: {$in: [1, 3]}}) // 使用$in操作符来查找等级等于1或3的用户
[
{
_id: ObjectId('661a2f4188cec2c9eeef634b'),
name: '刘备',
email: 'liubei@qq.com',
level: 1,
skills: [ '谋略', '领导' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634d'),
name: '张飞',
email: 'zhangfei@qq.com',
level: 3,
skills: [ '力量', '勇猛' ]
}
]
game>
game> db.users.find({level: {$nin: [1, 3]}}) // 使用$nin操作符来查找等级不等于1或3的用户
[
{ _id: ObjectId('660d78af3ded4220cc7b2dac'), name: 'lololowe' },
{ _id: ObjectId('660d7c9b3ded4220cc7b2dad'), name: '张三', age: '18' },
{ _id: ObjectId('660d7e253ded4220cc7b2dae'), name: '李四' },
{ _id: ObjectId('660d7e253ded4220cc7b2daf'), name: '王五' },
{
_id: ObjectId('661a2f4188cec2c9eeef634c'),
name: '关羽',
email: 'guanyu@qq.com',
level: 2,
skills: [ '武艺', '忠诚' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634e'),
name: '赵云',
email: 'zhaoyun@qq.com',
level: 4,
skills: [ '智勇', '忠诚' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634f'),
name: '曹操',
email: 'caocao@qq.com',
level: 5,
skills: [ '智谋', '军事' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef6350'),
name: '孙权',
email: 'sunquan@qq.com',
level: 6,
skills: [ '勇猛', '智计' ]
}
]
game>
game> db.users.find({email: {$exists: 1}}) // 查询包含email字段的文档, 1也可替换为true
[
{
_id: ObjectId('661a2f4188cec2c9eeef634b'),
name: '刘备',
email: 'liubei@qq.com',
level: 1,
skills: [ '谋略', '领导' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634c'),
name: '关羽',
email: 'guanyu@qq.com',
level: 2,
skills: [ '武艺', '忠诚' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634d'),
name: '张飞',
email: 'zhangfei@qq.com',
level: 3,
skills: [ '力量', '勇猛' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634e'),
name: '赵云',
email: 'zhaoyun@qq.com',
level: 4,
skills: [ '智勇', '忠诚' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634f'),
name: '曹操',
email: 'caocao@qq.com',
level: 5,
skills: [ '智谋', '军事' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef6350'),
name: '孙权',
email: 'sunquan@qq.com',
level: 6,
skills: [ '勇猛', '智计' ]
}
]
game>
game> db.users.find({email: {$exists: 0}}) // 查询不包含email字段的文档, 0也可替换为false
[
{ _id: ObjectId('660d78af3ded4220cc7b2dac'), name: 'lololowe' },
{ _id: ObjectId('660d7c9b3ded4220cc7b2dad'), name: '张三', age: '18' },
{ _id: ObjectId('660d7e253ded4220cc7b2dae'), name: '李四' },
{ _id: ObjectId('660d7e253ded4220cc7b2daf'), name: '王五' }
]
game>
game> db.users.insertOne({name: "黄忠", email: null}) // 插入一个email字段为null的文档
{
acknowledged: true,
insertedId: ObjectId('661a3f0f88cec2c9eeef6351')
}
game>
game> db.users.find({email: {$exists: true}}) // 再次查询包含邮箱字段的文档,出现了刚插入email字段为空的用户,说明$exists操作符只能查询字段是否存在不能查询是否有值
[
{
_id: ObjectId('661a2f4188cec2c9eeef634b'),
name: '刘备',
email: 'liubei@qq.com',
level: 1,
skills: [ '谋略', '领导' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634c'),
name: '关羽',
email: 'guanyu@qq.com',
level: 2,
skills: [ '武艺', '忠诚' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634d'),
name: '张飞',
email: 'zhangfei@qq.com',
level: 3,
skills: [ '力量', '勇猛' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634e'),
name: '赵云',
email: 'zhaoyun@qq.com',
level: 4,
skills: [ '智勇', '忠诚' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634f'),
name: '曹操',
email: 'caocao@qq.com',
level: 5,
skills: [ '智谋', '军事' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef6350'),
name: '孙权',
email: 'sunquan@qq.com',
level: 6,
skills: [ '勇猛', '智计' ]
},
{
_id: ObjectId('661a3f0f88cec2c9eeef6351'),
name: '黄忠',
email: null // email字段即使为空也可以查询到
}
]
game>
game> db.users.find({level: {$gte: 3, $lte: 5}}) // 组合使用$gte操作符和$lte操作符来查找等级大于等于3且小于等于5的用户, gte表示大于等于(greater than or equal), lte表示小于等于(less than or equal)
[
{
_id: ObjectId('661a2f4188cec2c9eeef634d'),
name: '张飞',
email: 'zhangfei@qq.com',
level: 3,
skills: [ '力量', '勇猛' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634e'),
name: '赵云',
email: 'zhaoyun@qq.com',
level: 4,
skills: [ '智勇', '忠诚' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634f'),
name: '曹操',
email: 'caocao@qq.com',
level: 5,
skills: [ '智谋', '军事' ]
}
]
game>
game> db.users.find({$and: [{level: {$gte: 3}}, {level: {$lte: 5}}]}) // 使用$and操作符来组合查询条件,查找等级大于等于3且小于等于5的用户
[
{
_id: ObjectId('661a2f4188cec2c9eeef634d'),
name: '张飞',
email: 'zhangfei@qq.com',
level: 3,
skills: [ '力量', '勇猛' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634e'),
name: '赵云',
email: 'zhaoyun@qq.com',
level: 4,
skills: [ '智勇', '忠诚' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634f'),
name: '曹操',
email: 'caocao@qq.com',
level: 5,
skills: [ '智谋', '军事' ]
}
]
game>
game> db.users.find({$or: [{level: {$gte: 3}}, {level: {$lte: 5}}]}) // 使用$or操作符来组合查询条件,查找等级大于等于3或小于等于5的用户
[
{
_id: ObjectId('661a2f4188cec2c9eeef634b'),
name: '刘备',
email: 'liubei@qq.com',
level: 1,
skills: [ '谋略', '领导' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634c'),
name: '关羽',
email: 'guanyu@qq.com',
level: 2,
skills: [ '武艺', '忠诚' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634d'),
name: '张飞',
email: 'zhangfei@qq.com',
level: 3,
skills: [ '力量', '勇猛' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634e'),
name: '赵云',
email: 'zhaoyun@qq.com',
level: 4,
skills: [ '智勇', '忠诚' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634f'),
name: '曹操',
email: 'caocao@qq.com',
level: 5,
skills: [ '智谋', '军事' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef6350'),
name: '孙权',
email: 'sunquan@qq.com',
level: 6,
skills: [ '勇猛', '智计' ]
}
]
game>
game> db.users.find({level: {$not: {$eq: 3}}}) // 使用$not操作符过滤等级为3的用户
[
{ _id: ObjectId('660d78af3ded4220cc7b2dac'), name: 'lololowe' },
{ _id: ObjectId('660d7c9b3ded4220cc7b2dad'), name: '张三', age: '18' },
{ _id: ObjectId('660d7e253ded4220cc7b2dae'), name: '李四' },
{ _id: ObjectId('660d7e253ded4220cc7b2daf'), name: '王五' },
{
_id: ObjectId('661a2f4188cec2c9eeef634b'),
name: '刘备',
email: 'liubei@qq.com',
level: 1,
skills: [ '谋略', '领导' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634c'),
name: '关羽',
email: 'guanyu@qq.com',
level: 2,
skills: [ '武艺', '忠诚' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634e'),
name: '赵云',
email: 'zhaoyun@qq.com',
level: 4,
skills: [ '智勇', '忠诚' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef634f'),
name: '曹操',
email: 'caocao@qq.com',
level: 5,
skills: [ '智谋', '军事' ]
},
{
_id: ObjectId('661a2f4188cec2c9eeef6350'),
name: '孙权',
email: 'sunquan@qq.com',
level: 6,
skills: [ '勇猛', '智计' ]
},
{
_id: ObjectId('661a3f0f88cec2c9eeef6351'),
name: '黄忠',
email: null
}
]
game>
game> db.users.find({name: {$regex: /张/, $options: 'i'}}) // 使用正则表达式操作符$regex查询名字中包含"张"的用户,$options: 'i'表示不区分大小写
[
{ _id: ObjectId('660d7c9b3ded4220cc7b2dad'), name: '张三', age: '18' },
{
_id: ObjectId('661a2f4188cec2c9eeef634d'),
name: '张飞',
email: 'zhangfei@qq.com',
level: 3,
skills: [ '力量', '勇猛' ]
}
]
game>
6.统计
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
game> db.users.countDocuments()  // 使用countDocuments()函数统计文档数量
11
game>
game> db.users.countDocuments({level: {$gte: 5}}) // 查询等级大于等于5的用户数量
2
game>
game> db.users.findOne({level: {$gte: 5}}) // 查询等级大于等于5的第一条文档
{
_id: ObjectId('661a2f4188cec2c9eeef634f'),
name: '曹操',
email: 'caocao@qq.com',
level: 5,
skills: [ '智谋', '军事' ]
}
game>
7.更新文档
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
game> db.users.updateOne({level: 1}, {$set: {money: 100}})  // 使用updateOne()函数更新第一个符合level为1的文档,设置money字段为100(若该字段不存在,则MongoDB会自动创建并修改该字段)
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
game>
game> db.users.findOne({level: 1}) // 查询level为1的文档,money字段的值已被修改为100
{
_id: ObjectId('661a2f4188cec2c9eeef634b'),
name: '刘备',
email: 'liubei@qq.com',
level: 1,
skills: [ '谋略', '领导' ],
money: 100
}
game>
game> db.users.updateOne({_id: ObjectId('661a2f4188cec2c9eeef634b')}, {$set: {money: 99}}) // 一般来说,更新数据都是使用_id来更新的
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
game>
game> db.users.findOne({level: 1}) // 可以看到money为99
{
_id: ObjectId('661a2f4188cec2c9eeef634b'),
name: '刘备',
email: 'liubei@qq.com',
level: 1,
skills: [ '谋略', '领导' ],
money: 99
}
game>
game> db.users.updateMany({level: 2}, {$set: {money: 66}}) // 使用updateMany()函数更新所有符合level为1的文档,设置money字段为66(若该字段不存在,则MongoDB会自动创建并修改该字段)
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
game>
game> db.users.find({level: 2}) // 查询所有等级为2的用户,可以看到money字段的值已被修改为66
[
{
_id: ObjectId('661a2f4188cec2c9eeef634c'),
name: '关羽',
email: 'guanyu@qq.com',
level: 2,
skills: [ '武艺', '忠诚' ],
money: 66
}
]
game>
8.删除文档
1
2
3
4
5
6
7
8
9
10
11
game> db.users.deleteOne({level: 1})  // 使用deleteOne()函数删除找到的第一个符合等级为1的条件的文档
{ acknowledged: true, deletedCount: 1 }
game>
game> db.users.findOne({level: 1}) // 查询等级为1的用户,可以看到已经没有结果了
null
game>
game> db.users.deleteMany({level: 2}) // 使用deleteMany()函数删除所有找到的等级为1的文档
{ acknowledged: true, deletedCount: 1 }
game> db.users.findOne({level: 2}) // 查询等级为2的用户,可以看到已经没有结果了
null
game>

参考视频:

https://www.bilibili.com/video/BV16u4y1y7Fm/