MongoDB数据库增删改查基本使用
# MongoDB数据库增删改查基本使用
@[TOC]
## 1.CRUD介绍
CRUD操作是create(创建)、read(读取)、update(更新)和delete(删除)
MongoDB不支持常规的SQL的命令,但是自身有丰富的查询语言
MongoDB在插入一条数据后,会自动增加一个_id自动,作为主键,如果插入的文档省略了id字段,则会自动生产一个Object_id字段
**MongoDB默认有4个数据库:**
test:登陆时默认存在的库,不切换其他库时默认存在的库
admin:系统预留库,MongoDB系统管理库
local:本地预留库,存储关键日志
config:MongoDB配置信息库
mongo默认登陆的时候是在test库下
mongo不需要提前创建库和表,直接use切换就是创建库,直接插入数据就会创建表
使用use切换到的库,如果没有任何数据,实际上并不会真正创建,是个虚的库,所以show dbs并不会显现,只有在插入数据后,数据库才会真正创建
mongodb插入数字时,不需要使用双引号
## 2.MongoDB数据库常用命令
| 命令 | 含义 |
| -------------------- | ------------------ |
| show databases | 查看数据库 |
| db | 显示当前所在数据库 |
| use config | 切换数据库 |
| help | 显示帮助信息 |
| db.help() | 显示数据库帮助信息 |
| show users | 查看所有用户 |
| show tables | 查看所有表 |
| db.表名.drop() | 删除一个表 |
| db.表名.insert() | 插入一条数据 |
| db.表名.insertMany() | 插入多条数据 |
| db.表名.find() | 查询数据 |
| db.表名.updateOne() | 更新一条数据 |
| db.表名.updateMany() | 更新多条数据 |
| db.表名.update() | 更新一条数据 |
| db.表名.deleteOne() | 删除一条数据 |
| db.表名.deleteMany() | 删除多条数据 |
## 3.MongoDB数据库显示命令
### 3.1.查询当前有多少个数据库
```sql
> show databases
admin 0.000GB
config 0.000GB
local 0.000GB
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
```
### 3.2.显示当前所在的数据库
```sh
> db
test
```
### 3.3.切换数据库
```sh
> use config
switched to db config
> db
config
```
### 3.4.显示帮助信息
```sh
1.显示当前库下可以执行的命令
> help
2.显示数据库操作命令
> db.help()
```
### 3.5.打印当前数据库用户列表
```sh
> show users
```
### 3.5.显示当前所在的数据库表信息
```sh
> show tables
```
### 3.6.删除一个表(集合)
```sql
> db.biao.drop()
true
```
### 3.8.命令行执行mongo命令
```bash
mongo --port 28017 --eval "show dbs"
echo "show dbs"|mongo --port 28017
```
## 4.插入数据
### 4.1.插入一条数据
mongodb数据库创建一个表,直接使用use命令进行就创建了,如果里面建了表,在show dbs的时候才能看到,否则没有数据的情况下是看不到的
插入数据时不需要先创建表,在插入数据时会自动将表创建出来
**语法格式:** db.表名.insert({"字段1":"值1","字段2":"值2"})
```sh
1.进入我们要创建数据的库
> use db_data
switched to db db_data
2.在user_info表中插入数据
> db.user_info.insert({"name":"jiangxl","ad":"北京市","job":"linux"})
WriteResult({ "nInserted" : 1 })
> db.user_info.insert({"name":"xiaoming","ad":"石家庄市","job":"net"})
WriteResult({ "nInserted" : 1 })
> db.user_info.insert({"name":"xiaolan","ad":"太原市","job":"java"})
WriteResult({ "nInserted" : 1 })
> db.user_info.insert({"name":"xiaozi","ad":"石家庄市","job":"guanggao"})
WriteResult({ "nInserted" : 1 })
3.查看表是否创建成功
> show tables
user_info
4.查看表中的数据
> db.user_info.find()
```
![在这里插入图片描述](https://img-blog.csdnimg.cn/7c348a64d99f4f49998d477eb99cb82c.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBASmlhbmd4bH4=,size_20,color_FFFFFF,t_70,g_se,x_16)
表中的数据在插入时会自动生成一个_id字段作为主键,数据格式也是json格式
在user_info表中插入不同字段的数据
```sh
> db.user_info.insert({"name":"xiaoqiang","ad":"北京市朝阳区","job":"linux","sex":"boy","xinzi":"10k"})
WriteResult({ "nInserted" : 1 })
> db.user_info.insert({"name":"xiaowu","ad":"北京市东城区","job":"linux","sex":"boy","xinzi":"6k"})
WriteResult({ "nInserted" : 1 })
```
可以看到,不同的字段只要表名相同都可以插在一个表中,而mysql只能更新表结构才能达到这种效果
应用如果更新涉及到了新增某个表的字段,mongod只需要在下次插入数据时,指定上新字段即可生效
![在这里插入图片描述](https://img-blog.csdnimg.cn/e30e033c9b994c478c23b762d5653f07.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBASmlhbmd4bH4=,size_20,color_FFFFFF,t_70,g_se,x_16)
### 4.2.批量插入多条数据
语法格式:db.表名.insertMany([{"字段1":"值1","字段2":"值2"},{"字段1":"值1","字段2":"值2"}])
使用insertMany插入的数据,会自动生产ObjectId
```sh
> db.book_date.insertMany([
{ "name":"nginx", "price":25, "num":100, "status":"N" },
{ "name":"ansible", "price":50, "num":200 , "status":"A" },
{ "name":"tomcat", "price":100, "num":150, "status":"T" },
{ "name":"redis", "price":75, "num":320 , "status":"R" },
{ "name":"docker", "price":45, "num":270, "status":"D" }
]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("602791d60ae90b3ed52d0247"),
ObjectId("602791d60ae90b3ed52d0248"),
ObjectId("602791d60ae90b3ed52d0249"),
ObjectId("602791d60ae90b3ed52d024a"),
ObjectId("602791d60ae90b3ed52d024b")
]
}
>
> show tables;
book_date
user_info
>
> db.book_date.find()
```
### 4.3.插入嵌套数据
```sh
> db.nest_date.insertMany( [
... { "item": "journal", "qty": 25, "size": { "h": 14, "w": 21, "uom": "cm" }, "status": "A" },
... { "item": "notebook", "qty": 50, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "A" },
... { "item": "paper", "qty": 100, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "D" },
... { "item": "planner", "qty": 75, "size": { "h": 22.85, "w": 30, "uom": "cm" }, "status": "D" },
... { "item": "postcard", "qty": 45, "size": { "h": 10, "w": 15.25, "uom": "cm" }, "status": "A" }
... ]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("60279b0d0ae90b3ed52d0251"),
ObjectId("60279b0d0ae90b3ed52d0252"),
ObjectId("60279b0d0ae90b3ed52d0253"),
ObjectId("60279b0d0ae90b3ed52d0254"),
ObjectId("60279b0d0ae90b3ed52d0255")
]
}
> show tables;
book_date
nest_date
user_info
> db.nest_date.find()
{ "_id" : ObjectId("60279b0d0ae90b3ed52d0251"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }
{ "_id" : ObjectId("60279b0d0ae90b3ed52d0252"), "item" : "notebook", "qty" : 50, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "A" }
{ "_id" : ObjectId("60279b0d0ae90b3ed52d0253"), "item" : "paper", "qty" : 100, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "D" }
{ "_id" : ObjectId("60279b0d0ae90b3ed52d0254"), "item" : "planner", "qty" : 75, "size" : { "h" : 22.85, "w" : 30, "uom" : "cm" }, "status" : "D" }
{ "_id" : ObjectId("60279b0d0ae90b3ed52d0255"), "item" : "postcard", "qty" : 45, "size" : { "h" : 10, "w" : 15.25, "uom" : "cm" }, "status" : "A" }
```
![在这里插入图片描述](https://img-blog.csdnimg.cn/7157859ca53d41f68c9898e2bcc96c9d.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBASmlhbmd4bH4=,size_20,color_FFFFFF,t_70,g_se,x_16)
## 5.查询数据
4中插入了一些数据,可以简单的练习查询
可以使用Navicat连接mongodb进行数据查询
find查询默认是and
语法格式:db.表名.find({"条件1":"值1","条件2,":"值2"})
db.表名.find({"条件1":"值1","条件2,":"{$lt:"值2"}})
或者查询
db.表名.find({$or: [{"条件1": "值1"},{"条件2": {$lt: 值2}}]})
### 5.1.查询book_date表中status包含N的数据
```sh
> db.book_date.find({"status":"N"})
{ "_id" : ObjectId("602792a80ae90b3ed52d024c"), "name" : "nginx", "price" : 25, "num" : 100, "status" : "N" }
```
navicat查询
![在这里插入图片描述](https://img-blog.csdnimg.cn/434997dcd0944d53a18596d895b36b9e.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBASmlhbmd4bH4=,size_20,color_FFFFFF,t_70,g_se,x_16)
### 5.2.查询nest_date表中size嵌套uom是cm并且qty小于50的数据
nest_date表中的size字段的数据时嵌套数据,因此在查询字段中嵌套的数据时需要使用"size.uom":"cm"
```sh
> db.nest_date.find({"size.uom":"cm","qty":{$lt:50}})
{ "_id" : ObjectId("60279b0d0ae90b3ed52d0251"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }
{ "_id" : ObjectId("60279b0d0ae90b3ed52d0255"), "item" : "postcard", "qty" : 45, "size" : { "h" : 10, "w" : 15.25, "uom" : "cm" }, "status" : "A" }
也可以使用Navicat拆一下显得好看
db.nest_date.find({
"size.uom": "cm", //size等于cm
"qty": {
$lt: 50 //qty小于50
}
})
```
navicat查询
![在这里插入图片描述](https://img-blog.csdnimg.cn/9c97e3446177493ba133ca1235fcfc3f.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBASmlhbmd4bH4=,size_20,color_FFFFFF,t_70,g_se,x_16)
### 5.3.查询nest_date表中size嵌套uom是cm并且qty等于75的数据
```sh
> db.nest_date.find({
... "size.uom": "cm",
... "qty": {
... $eq: 75
... }
... })
{ "_id" : ObjectId("60279b0d0ae90b3ed52d0254"), "item" : "planner", "qty" : 75, "size" : { "h" : 22.85, "w" : 30, "uom" : "cm" }, "status" : "D" }
解释:
db.nest_date.find({
"size.uom": "cm", //uom为cm的
"qty": {
$eq: 75 //qty等于75的
}
})
```
navicat查询
![在这里插入图片描述](https://img-blog.csdnimg.cn/12b7864e320a4612bab5a12880727e11.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBASmlhbmd4bH4=,size_20,color_FFFFFF,t_70,g_se,x_16)
### 5.4.查询book_date表status等于T或者price小于50的数据
```sh
> db.book_date.find({$or: [{"status": "T"},{"price": {$lt: 50}}]})
{ "_id" : ObjectId("602792a80ae90b3ed52d024c"), "name" : "nginx", "price" : 25, "num" : 100, "status" : "N" }
{ "_id" : ObjectId("602792a80ae90b3ed52d024e"), "name" : "tomcat", "price" : 100, "num" : 150, "status" : "T" }
{ "_id" : ObjectId("602792a80ae90b3ed52d0250"), "name" : "docker", "price" : 45, "num" : 270, "status" : "D" }
解释:
db.book_date.find({
$or: [ //或者
{
"status": "T" //staus等于T的
},
{
"price": {
$lt: 50 //price小于50的
}
}
]
})
```
navicat查询
![在这里插入图片描述](https://img-blog.csdnimg.cn/7141016375d24bb3805158ed5d377e77.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBASmlhbmd4bH4=,size_20,color_FFFFFF,t_70,g_se,x_16)
### 5.5.正则查询表中数据
查询book_date表中status为D并且price小于50和name以do开头两者满足其一的数据
```sh
> db.book_date.find({"status":"D",$or: [{"price":{$lt:30}},{"name": /^do/}]})
{ "_id" : ObjectId("602792a80ae90b3ed52d0250"), "name" : "docker", "price" : 45, "num" : 270, "status" : "D" }
解释:
db.book_date.find({
"status": "D", //status为D的
$or: [{
"price": { //price小于30的
$lt: 30
}
}, {
"name": /^do/ //name以do开头的
}]
})
```
navicat查询
![在这里插入图片描述](https://img-blog.csdnimg.cn/a86a5a33141d4904953ae497c6431e20.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBASmlhbmd4bH4=,size_20,color_FFFFFF,t_70,g_se,x_16)
### 5.6.查询表中第一条数据
```sh
> db.book_date.findOne()
{
"_id" : ObjectId("602792a80ae90b3ed52d024c"),
"name" : "nginx",
"price" : 25,
"num" : 100,
"status" : "N"
}
```
![在这里插入图片描述](https://img-blog.csdnimg.cn/84b1a4b187eb4110a39d42b2962d232a.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBASmlhbmd4bH4=,size_20,color_FFFFFF,t_70,g_se,x_16)
## 6.更新数据
mongodb更新一条数据后,会在最后增加一个新的字段,记录更新的时间
语法格式:
更新一条数据:db.表名.updateOne({"匹配条件1":"值"1},{$set:{"更新的字段1":"新值1","更新字段2":"新值2"},$currentDate:{"lastModified":true}})
更新多条数据:db.表名.updateMany({"匹配条件1":"值"1},{$set:{"更新的字段1":"新值1","更新字段2":"新值2"},$currentDate:{"lastModified":true}})
使用update更新:db.表名.update({"匹配条件1":"值"1},{$set:{"更新的字段1":"新值1","更新字段2":"新值2"},$currentDate:{"lastModified":true}})
更新多条数据:
### 6.1.更新一条数据
将name等于nginx的数据中的price改为70,num改为230
```sh
1.查询要更新的数据
> db.book_date.find({"name":"nginx"})
{ "_id" : ObjectId("602792a80ae90b3ed52d024c"), "name" : "nginx", "price" : 25, "num" : 100, "status" : "N" }
2.更新语句
> db.book_date.updateOne({"name":"nginx"},{$set:{"price":70,"num":230},$currentDate:{"lastModified":true}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
3.查看数据是否更新
> db.book_date.find()
{ "_id" : ObjectId("6027de7f0ae90b3ed52d0256"), "name" : "nginx", "price" : 70, "num" : 230, "status" : "N", "lastModified" : ISODate("2021-02-13T14:14:01.526Z") }
{ "_id" : ObjectId("6027de7f0ae90b3ed52d0257"), "name" : "ansible", "price" : 50, "num" : 200, "status" : "A" }
{ "_id" : ObjectId("6027de7f0ae90b3ed52d0258"), "name" : "tomcat", "price" : 100, "num" : 150, "status" : "T" }
{ "_id" : ObjectId("6027de7f0ae90b3ed52d0259"), "name" : "redis", "price" : 75, "num" : 320, "status" : "R" }
{ "_id" : ObjectId("6027de7f0ae90b3ed52d025a"), "name" : "docker", "price" : 45, "num" : 270, "status" : "D" }
```
![在这里插入图片描述](https://img-blog.csdnimg.cn/abd25c12ae814f5cbfbaf5993acc673f.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBASmlhbmd4bH4=,size_20,color_FFFFFF,t_70,g_se,x_16)
更新语句解释
```sh
db.book_date.updateOne({
"name": "nginx" //要匹配的数据,当数据中name是nginx的数据
}, {
$set: { //要修改的内容
"price": 70, //price修改为70
"num": 230 //num修改为230
},
$currentDate: {
"lastModified": true //增加一个字段,每次更新都记录时间
}
})
```
### 6.2.匹配多个条件更新
将name等于nginx并且status等于N的数据进行更新,将price修改为70,num修改为230,status修改为Nginx
```sh
db.book_date.updateOne({
"name": "nginx", //条件1
"status":"N" //条件2
}, {
$set: { //更新的内容
"price": 70,
"num": 230,
"status":"Nginx"
},
$currentDate: {
"lastModified": true
}
})
```
更新成功
![在这里插入图片描述](https://img-blog.csdnimg.cn/05c7cdc30f2d45f98d8650c7c09b452d.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBASmlhbmd4bH4=,size_20,color_FFFFFF,t_70,g_se,x_16)
### 6.3.更新多条数据
num小于250的数据,将price修改为99,num修改为530
```sh
> db.book_date.updateMany({"num":{$lt:250}},{$set:{"price":"99","num":"530"},$currentDate:{"lastModified":true}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.book_date.find()
{ "_id" : ObjectId("602792a80ae90b3ed52d024c"), "name" : "nginx", "price" : "70", "num" : "230", "status" : "Nginx", "lastModified" : ISODate("2021-02-13T11:19:38.473Z") }
{ "_id" : ObjectId("602792a80ae90b3ed52d024d"), "name" : "ansible", "price" : "99", "num" : "530", "status" : "A", "lastModified" : ISODate("2021-02-13T11:24:46.045Z") }
{ "_id" : ObjectId("602792a80ae90b3ed52d024e"), "name" : "tomcat", "price" : "99", "num" : "530", "status" : "T", "lastModified" : ISODate("2021-02-13T11:23:59.063Z") }
{ "_id" : ObjectId("602792a80ae90b3ed52d024f"), "name" : "redis", "price" : 75, "num" : 320, "status" : "R" }
{ "_id" : ObjectId("602792a80ae90b3ed52d0250"), "name" : "docker", "price" : 45, "num" : 270, "status" : "D" }
解释:
db.book_date.updateMany({
"num": {
$lt: 300 //num小于300的全部数据
}
}, {
$set: {
"price": "99", //price更新为99
"num": "530" //num更新为530
},
$currentDate: {
"lastModified": true
}
})
```
更新成功
![在这里插入图片描述](https://img-blog.csdnimg.cn/22d0eaf0a5a74989b709bd503f52a721.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBASmlhbmd4bH4=,size_20,color_FFFFFF,t_70,g_se,x_16)
### 6.4.使用update更新一条数据
```sh
db.book_date.update({
"name": "nginx"
}, {
$set: {
"price": "70",
"num": "230",
"status":"nginx"
},
$currentDate: {
"lastModified": true
}
})
```
![在这里插入图片描述](https://img-blog.csdnimg.cn/5b9ab9a6dabf4c2eadaeeee0fb437755.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBASmlhbmd4bH4=,size_20,color_FFFFFF,t_70,g_se,x_16)
## 7.删除数据
语法格式:
删除一个:db.表名.deleteOne({"条件1":"值1"})
删除多个:db.表名.deleteMany({"条件1":"值1"})
### 7.1.删除一条数据
```sh
> db.book_date.deleteOne({"name":"nginx"})
{ "acknowledged" : true, "deletedCount" : 1 }
```
![在这里插入图片描述](https://img-blog.csdnimg.cn/0712b42d45be49eab9116ec89e9c3d39.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBASmlhbmd4bH4=,size_20,color_FFFFFF,t_70,g_se,x_16)
### 7.2.删除多条数据
```sh
> db.book_date.deleteMany({"num":{$lt:500}})
{ "acknowledged" : true, "deletedCount" : 2 }
```
![在这里插入图片描述](https://img-blog.csdnimg.cn/26b0e4a78d5f434b860921a49253bc62.png)
- 点赞
- 收藏
- 关注作者
评论(0)