MongoDB的基本操作介绍、数据库/表的创建和删除、数据的查询

在这里插入图片描述


MongoDB的基本操作介绍

一、基础操作

1.1 连接数据库

终端输入mongo命令,输出类似如下内容就证明已经和数据库建立了连接。

PS E:\Code> mongo
MongoDB shell version v5.0.8
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("ebcefcb0-f345-460d-94fd-0ea7cf525c6f") }
MongoDB server version: 5.0.8
================
Warning: the "mongo" shell has been superseded by "mongosh",which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
For installation instructions,see
https://docs.mongodb.com/mongodb-shell/install/
================
---
The server generated these startup warnings when booting:
        2022-07-16T07:08:30.841+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
---
---
        Enable MongoDB's free cloud-based monitoring service,which will then receive and display
        metrics about your deployment (disk utilization,CPU,operation statistics,etc).

        The monitoring data will be available on a MongoDB website with a unique URL accessible to you
        and anyone you share the URL with. MongoDB may use this information to make product
        improvements and to suggest MongoDB products and deployment options to you.

        To enable free monitoring,run the following command: db.enableFreeMonitoring()
        To permanently disable this reminder,run the following command: db.disableFreeMonitoring()
---
>

1.2 查看数据库

使用show dbs可以查看当前MongoDB有哪些数据库。

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

新安装的MongoDB默认存在三个数据库,即adminconfiglocal,保持不变即可,不要操作这三个数据库。

1.3 创建数据库

实际上,MongoDB的数据库是不需要专门去创建的,我们可以直接使用一个不存在的数据库,这样就会自动创建这个不存在的数据库。这样,创建一个数据库就需要两步:

  1. use db_name,表明要创建的数据库名称db_name
  2. db.tb_name.insert(),向表tb_name中插入一条数据;

这样就创建了一个数据库,同时,顺带的也就创建了一个名为tb_name的表。

举个例子,我们现在需要创建一个名为db_ahoh的数据库,并向tb_user表中插入数据,需要执行以下操作:

> use db_ahoh
switched to db db_ahoh
> db.tb_user.insert({username:'张三',age:18})
WriteResult({ "nInserted" : 1 })
>

这样我们就创建了一个名为db_ahoh的数据库,同时还有一个名为tb_user的表(集合)。

此时,我们可以使用show dbs命令查看数据库的状态:

> show dbs
admin    0.000GB
config   0.000GB
db_ahoh  0.000GB   (*)
local    0.000GB

此时,数据库db_ahoh已经创建完成了。

1.4 查看数据表(集合)

如果我们想要查看一个数据库中有哪些表,需要使用show collections命令。

在此之前,需要先用use db_name命令指定要查看的表。

举个例子,我们要查看数据库db_ahoh中表的数量,操作如下:

> use db_ahoh          # 如果上面用过了,这里可以省略
switched to db db_ahoh
> show collections
tb_user

这样我们就看到了,数据库db_ahoh中存在一个表tb_user

1.5 检索表中的所有数据

类似于关系数据库中的select * from tb_name,我们可以使用db.tb_name.find()查询表中所有的数据。

举个例子,查询数据表tb_user中所有的数据:

> db.tb_user.find()
{ "_id" : ObjectId("62d3d4b79e0562d1e456d9de"),"username" : "张三","age" : 18 }

可以看到,里面有我们之前在创建数据库时插入的一条数据。

1.6 新建数据表、插入数据

和数据库一样,数据表其实也是不需要提前创建的,在使用的时候可以直接使用db.tb_name.insert()插入数据即可,如果表不存在,就会创建该表。

举个例子,创建一个名为tb_admin的表:

> db.tb_admin.insert({username:'李四',age:11})   # 创建并插入数据
WriteResult({ "nInserted" : 1 })
> show collections
tb_admin
tb_user
> db.tb_admin.find()
{ "_id" : ObjectId("62d3d7099e0562d1e456d9df"),"username" : "李四","age" : 11 }

1.7 删除数据表

使用db.tb_name.drop()删除指定的数据表。

举个例子,删除名为tb_admin的数据表:

> db.tb_admin.drop()
true
> show collections
tb_user

在执行drop()指令后,查看数据表的个数,就可以发现tb_admin已经被删除了。

1.8 删除数据库

使用db.dropDatabase()指令直接删除当前使用的数据。

举个例子,删除db_admin数据:

> show dbs
admin    0.000GB
config   0.000GB
db_ahoh  0.000GB       # 删除之前
local    0.000GB
> db.dropDatabase()    # 删除数据库
{ "ok" : 1 }
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

二、数据检索

在学习检索之前,我们先建立一个新的数据库,并插入数据,代码如下:

use db_adoh
db.tb_user.insert({username:"小明",age:12})
db.tb_user.insert({username:"小红",age:31})
db.tb_user.insert({username:"明凯",age:12})
db.tb_user.insert({username:"秀红",age:22})

2.1 查找所有数据

此时表中的数据:

> db.tb_user.find()
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e4"),"username" : "小明","age" : 12 }
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e5"),"username" : "小红","age" : 31 }
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e6"),"username" : "明凯","age" : 12 }
{ "_id" : ObjectId("62d3dc969e0562d1e456d9e7"),"username" : "秀红","age" : 22 }

2.2 查找age=12的数据

find()传入{age:12}表示查找age=12的数据:

> db.tb_user.find({age:12})
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e4"),"age" : 12 }
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e6"),"age" : 12 }

类似的,查找username="小明"的数据:

> db.tb_user.find({username:"小明"})
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e4"),"age" : 12 }

2.3 查找age>22的数据

find()传入参数{age:{$gt:22}}表示age>22

> db.tb_user.find({age:{$gt:22}})
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e5"),"age" : 31 }

$gt:22表示Greater than 22

2.4 查找age<22的数据

find()传入参数{age:{$lt:22}}表示age<22

> db.tb_user.find({age:{$lt:22}})
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e4"),"age" : 12 }

$lt:22表示Less than 22

2.5 查找age>=22的数据

find()传入参数{age:{$gte:22}}表示age>=22

> db.tb_user.find({age:{$gte:22}})
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e5"),"age" : 31 }
{ "_id" : ObjectId("62d3dc969e0562d1e456d9e7"),"age" : 22 }

或者传入参数{age:{$lte:22}}查找age<=22的数据:

> db.tb_user.find({age:{$lte:22}})
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e4"),"age" : 22 }

$gt$lt后面加上e$gte$lte表示大于等于/小于等于。

2.6 查找age>=12,且age<=30的数据

find()传入参数{age:{$gte:12,$lte:30}}表示12=<age<=30

> db.tb_user.find({age:{$gte:12,$lte:30}})
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e4"),"age" : 22 }

使用{$gte:12,$lte:30}表示联合条件查询。

2.7 查找username中包含“明”字的数据

find()传入参数{username:/明/}表示username包含“明”字:

> db.tb_user.find({username:/明/})
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e4"),"age" : 12 }

2.8 查找username中以“明”开头的数据

find()传入参数{username:/^明/}表示以“明”开头的username

> db.tb_user.find({username:/^明/})
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e6"),"age" : 12 }

2.9 查找username中以“明”结尾的数据

find()传入参数{username:/明$/}表示以“明”结尾的username

> db.tb_user.find({username:/明$/})
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e4"),"age" : 12 }

2.10 只查找username或者age列中的数据

find()传入参数{username:1}表示只查询username数据:

> db.tb_user.find({},{username:1})
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e4"),"username" : "小明" }
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e5"),"username" : "小红" }
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e6"),"username" : "明凯" }
{ "_id" : ObjectId("62d3dc969e0562d1e456d9e7"),"username" : "秀红" }

这样我们就得到了所有username数据,而且不包含age

还可以查找符合特定条件的指定列数据,例如,查找age>12username

> db.tb_user.find({age:{$gt:12}},{username:1})
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e5"),"username" : "小红" }
{ "_id" : ObjectId("62d3dc969e0562d1e456d9e7"),"username" : "秀红" }

find()函数的第二个参数中设置为1的属性会被查找。

2.11 按照年龄排序查询结果

使用.sort({age:1})升序排列结果:

> db.tb_user.find().sort({age:1})
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e4"),"age" : 22 }
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e5"),"age" : 31 }

年龄从上到下增加。

使用.sort({age:-1})降序排列结果:

> db.tb_user.find().sort({age:-1})
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e5"),"age" : 22 }
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e4"),"age" : 12 }

年龄从上到下递减。

2.12 查询username=“小明”,age=12的数据

再插入一个username为“小明”,age16的数据,然后查找username=小明age=12的数据:

> db.tb_user.insert({username:'小明',age:16}))
WriteResult({ "nInserted" : 1 })
> db.tb_user.find({username:"小明",age:12})
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e4"),"age" : 12 }

2.13 查找前3条数据

使用limit(num)限制查询结果的数量:

> db.tb_user.find().limit(3)
{ "_id" : ObjectId("62d3dc949e0562d1e456d9e4"),"age" : 12 }

2.14 查找3条数据之后的数据

使用skip(num)跳过结果中的前num条数据:

> db.tb_user.find().skip(3)
{ "_id" : ObjectId("62d3dc969e0562d1e456d9e7"),"age" : 22 }
{ "_id" : ObjectId("62d3ef1b9e0562d1e456d9e8"),"age" : 16 }

三、总结

  1. 基础的数据库创建、删除指令
  2. 基础的数据增、删、改、查指令
  3. 基础的查找指令

相关文章

文章浏览阅读552次。com.mongodb.MongoQueryException: Quer...
文章浏览阅读635次,点赞9次,收藏8次。MongoDB 是一种 NoSQ...
文章浏览阅读2.1k次。和。_mongodb 日期类型
文章浏览阅读1.7k次。Scalestack等客户期待使用MongoDB Atla...
文章浏览阅读970次。SpringBoot整合中间件mongodb、ES_sprin...
文章浏览阅读673次。MongoDB 简介_尚医通sql