MongoDB 基本操作 增删改查

本文涉及的产品
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
简介: MongoDB 基本操作 增删改查

MongoDB 基本操作


当前文档基于 MongoDB server version: 4.0.20




0. MongoDB 特性


用MySQL 和 MongoDB 做比较

Database Database 数据库
Table Collection/Table 表/集合
MySQL MongoDB 说明
Row Document 行/文档
Column Field 字段/域



1. 数据库操作

在mongoDB中, 若数据库不存在,那么只有在库中向集合插入数据的时候才会创建


1.1 用法


查看数据库show dbs

指定数据库use Database

查看当前数据库

默认情况下,当前数据库是test

db


删除数据库

在操作此步骤之前,应当使用 db 确认一下库名

执行dropDatabase() 操作后,当前选择的数据库依然是这个库,只不过是在内存中而已。

db.dropDatabase()


查看数据库版本

db.version()


查看当前库统计信息

db.stats()


1.2 例子

查看当前有哪些数据库

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


查看当前数据库

> db
test
>


创建一个数据库并且查看

> use LearnDB
switched to db LearnDB
> 
> db
LearnDB
>


删除数据库

> db.dropDatabase()
{ "ok" : 1 }
>


查看数据库版本

> db.version()
4.0.20
>

查看当前库统计信息

> db.stats()
{
        "db" : "LearnDB",
        "collections" : 0,
        "views" : 0,
        "objects" : 0,
        "avgObjSize" : 0,
        "dataSize" : 0,
        "storageSize" : 0,
        "numExtents" : 0,
        "indexes" : 0,
        "indexSize" : 0,
        "fileSize" : 0,
        "fsUsedSize" : 0,
        "fsTotalSize" : 0,
        "ok" : 1
}
>




2. 集合操作

默认情况下,mongo在插入文档的时候,集合默认会被创建



2.1 用法


查看当前库的集合

show collections

插入单条数据

db.CollectionName.insertOne()

插入多条数据

db.CollectionName.insertMany()

删除集合

db.CollectionName.drop()

修改集合名称

db.CollectionName.renameCollection()

创建集合

db.createCollection()


2.2 例子


插入单条数据

> db.stu_info.insertOne({"std_name":"小明","sex":"男","reg_time":Date()})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61d6b4afa5a7b57ea8e0a9db")
}


查看当前库的集合

> show collections
stu_info
>

插入多条数据

>  db.stu_info.insertMany([{"std_name":"小刚","sex":"男","reg_time":Date()},{"std_name":"小红","sex":"女","reg_time":Date()}])
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("61d6b59da5a7b57ea8e0a9dc"),
                ObjectId("61d6b59da5a7b57ea8e0a9dd")
        ]
}
>


删除集合

> db.stu_info.drop()
true
>

修改集合名称

> db.stu_info.renameCollection("stuInfo")
{ "ok" : 1 }
> show collections
stuInfo
>


创建集合

默认情况下,向集合中插入数据,会默认创建,还有一种情况,是设置集合为 容量上限模式 ,则需要提前创建

语法

db.createCollection(<name>, { capped: <boolean>,
                              autoIndexId: <boolean>,
                              size: <number>,
                              max: <number>,
                              storageEngine: <document>,
                              validator: <document>,
                              validationLevel: <string>,
                              validationAction: <string>,
                              indexOptionDefaults: <document>,
                              viewOn: <string>,
                              pipeline: <pipeline>,
                              collation: <document>,
                              writeConcern: <document>} )
name: 集合名称
capped: 若为true,则创建 有上限模式 的集合
size: 设置上限的最大大小,以字节为单位,若达到最大值,则会删除旧文档
max: 允许最大文档数,当同时设置 size 和 max , 则 size 优先级 大于 max 


测试插入数据

可以发现,插入超过5条后,新插入的数据,会删除旧文档,然后插入新文档

>  db.std_log.insertMany([{"id":1,"status":true,"time":Date()},{"id":2,"status":false,"time":Date()},{"id":3,"status":true,"time":Date()},{"id":4,"status":true,"time":Date()},{"id":5,"status":false,"time":Date()}])
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("61d6c44da5a7b57ea8e0aa01"),
                ObjectId("61d6c44da5a7b57ea8e0aa02"),
                ObjectId("61d6c44da5a7b57ea8e0aa03"),
                ObjectId("61d6c44da5a7b57ea8e0aa04"),
                ObjectId("61d6c44da5a7b57ea8e0aa05")
        ]
}
> db.std_log.find()
{ "_id" : ObjectId("61d6c44da5a7b57ea8e0aa01"), "id" : 1, "status" : true, "time" : "Thu Jan 06 2022 18:28:29 GMT+0800 (CST)" }
{ "_id" : ObjectId("61d6c44da5a7b57ea8e0aa02"), "id" : 2, "status" : false, "time" : "Thu Jan 06 2022 18:28:29 GMT+0800 (CST)" }
{ "_id" : ObjectId("61d6c44da5a7b57ea8e0aa03"), "id" : 3, "status" : true, "time" : "Thu Jan 06 2022 18:28:29 GMT+0800 (CST)" }
{ "_id" : ObjectId("61d6c44da5a7b57ea8e0aa04"), "id" : 4, "status" : true, "time" : "Thu Jan 06 2022 18:28:29 GMT+0800 (CST)" }
{ "_id" : ObjectId("61d6c44da5a7b57ea8e0aa05"), "id" : 5, "status" : false, "time" : "Thu Jan 06 2022 18:28:29 GMT+0800 (CST)" }
> 
> db.std_log.insertOne({"id":6,"status":false,"time":Date()})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61d6c4b9a5a7b57ea8e0aa07")
}
> db.std_log.find()
{ "_id" : ObjectId("61d6c44da5a7b57ea8e0aa02"), "id" : 2, "status" : false, "time" : "Thu Jan 06 2022 18:28:29 GMT+0800 (CST)" }
{ "_id" : ObjectId("61d6c44da5a7b57ea8e0aa03"), "id" : 3, "status" : true, "time" : "Thu Jan 06 2022 18:28:29 GMT+0800 (CST)" }
{ "_id" : ObjectId("61d6c44da5a7b57ea8e0aa04"), "id" : 4, "status" : true, "time" : "Thu Jan 06 2022 18:28:29 GMT+0800 (CST)" }
{ "_id" : ObjectId("61d6c44da5a7b57ea8e0aa05"), "id" : 5, "status" : false, "time" : "Thu Jan 06 2022 18:28:29 GMT+0800 (CST)" }
{ "_id" : ObjectId("61d6c4b9a5a7b57ea8e0aa07"), "id" : 6, "status" : false, "time" : "Thu Jan 06 2022 18:30:17 GMT+0800 (CST)" }
>




3. 查询操作


3.1 用法


查询集合文档条数

db.CollectionNmae.count()


普通查询

db.CollectionName.find()


格式化显示

db.CollectionName.find().pretty()


比较查询

等于

db.CollectionName.find({k:v})

不等于

db.CollectionName.find({k:{$ne: v})

大于

db.CollectionName.find({k:{$gt: v})

小于

db.CollectionName.find({k:{$lt: v})

大于或等于

db.CollectionName.find({k:{$lte: v})

小于或等于

db.CollectionName.find({k:{$gte: v})

and | or 查询

and

db.CollectionName.find({k:v,k1:v1})

or

db.CollectionName.find({$or:[{k1:v1},{k2:v2}]})

and 和 or 联合查询

db.CollectionName.find({k:v,$or:[{k1:v1},{k2:v2}]})

排序查询

db.CollectionName.find().sort({k:1})


指定返回行数查询

db.CollectionName.find().limit()

db.CollectionName.find().skip()


指定返回域

db.CollectionName.find({k:v},{k1:1,k2:1})


只返回一条

db.CollectionName.findOne({k:v})


只返回一条并且删除该数据

db.CollectionName.findOneAndDelete({k:v})



3.2 例子


数据准备


> use LearnDB
switched to db LearnDB
> 
> db.dropDatabase()
{ "dropped" : "LearnDB", "ok" : 1 }
> 
> 
> db.stu_info.insertMany([
...     {"name": "小明" , "sex": "男" , "score1": 98 , "score2": 60, "score3": 79 , "score5": 101 , "classID: " : 1},
...     {"name": "小红" , "sex": "女" , "score1": 100 , "score2": 100, "score3": 100 , "score5": 80 , "classID: " : 3},
...     {"name": "小赵" , "sex": "女" , "score1": 80 , "score2": 79, "score3": 33 , "score5": 55 , "classID: " : 3},
...     {"name": "小钱" , "sex": "男" , "score1": 89 , "score2": 36, "score3": 102 , "score5": 65 , "classID: " : 5},
...     {"name": "小李" , "sex": "女" , "score1": 53 , "score2": 91, "score3": 34 , "score5": 19 , "classID: " : 9},
...     {"name": "小王" , "sex": "女" , "score1": 100 , "score2": 100, "score3": 100 , "score5": 99 , "classID: " : 1},
...     {"name": "小周" , "sex": "女" , "score1": 99 , "score2": 94, "score3": 92 , "score5": 90 , "classID: " : 6}
...     ])
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("61d6cac2a5a7b57ea8e0aa08"),
                ObjectId("61d6cac2a5a7b57ea8e0aa09"),
                ObjectId("61d6cac2a5a7b57ea8e0aa0a"),
                ObjectId("61d6cac2a5a7b57ea8e0aa0b"),
                ObjectId("61d6cac2a5a7b57ea8e0aa0c"),
                ObjectId("61d6cac2a5a7b57ea8e0aa0d"),
                ObjectId("61d6cac2a5a7b57ea8e0aa0e")
        ]
}
> 


查询集合文档条数

> db.stu_info.count()
7
>

普通查询

mongo shell 默认只返回10条,超过10条 需要 根据提示往下翻页

> db.stu_info.find()
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa08"), "name" : "小明", "sex" : "男", "score1" : 98, "score2" : 60, "score3" : 79, "score5" : 101, "classID: " : 1 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa09"), "name" : "小红", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 80, "classID: " : 3 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0a"), "name" : "小赵", "sex" : "女", "score1" : 80, "score2" : 79, "score3" : 33, "score5" : 55, "classID: " : 3 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0b"), "name" : "小钱", "sex" : "男", "score1" : 89, "score2" : 36, "score3" : 102, "score5" : 65, "classID: " : 5 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0c"), "name" : "小李", "sex" : "女", "score1" : 53, "score2" : 91, "score3" : 34, "score5" : 19, "classID: " : 9 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0d"), "name" : "小王", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 99, "classID: " : 1 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0e"), "name" : "小周", "sex" : "女", "score1" : 99, "score2" : 94, "score3" : 92, "score5" : 90, "classID: " : 6 }
> 


指定返回行数查询

查询2个文档

> db.stu_info.find().limit(2)
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa08"), "name" : "小明", "sex" : "男", "score1" : 98, "score2" : 60, "score3" : 79, "score5" : 101, "classID: " : 1 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa09"), "name" : "小红", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 80, "classID: " : 3 }
>


跳过第1个文档,查询1个文档

> db.stu_info.find().skip(1).limit(1)
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa09"), "name" : "小红", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 80, "classID: " : 3 }
>


格式化显示

> db.stu_info.find().pretty().limit(2)
{
        "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa08"),
        "name" : "小明",
        "sex" : "男",
        "score1" : 98,
        "score2" : 60,
        "score3" : 79,
        "score5" : 101,
        "classID: " : 1
}
{
        "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa09"),
        "name" : "小红",
        "sex" : "女",
        "score1" : 100,
        "score2" : 100,
        "score3" : 100,
        "score5" : 80,
        "classID: " : 3
}
> 

比较查询

等于: 查询 name 等于 小明 的文档

> db.stu_info.find({"name":"小明"})
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa08"), "name" : "小明", "sex" : "男", "score1" : 98, "score2" : 60, "score3" : 79, "score5" : 101, "classID: " : 1 }
>



不等于: 查询 name 不等于 小明 的文档,并且取出第一个

> db.stu_info.find({"name":{$ne:"小明"}}).limit(1).pretty()
{
        "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa09"),
        "name" : "小红",
        "sex" : "女",
        "score1" : 100,
        "score2" : 100,
        "score3" : 100,
        "score5" : 80,
        "classID: " : 3
}
>



大于: 查询 socre3 大于100 的文档

> db.stu_info.find({"score3":{$gt:100}})
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0b"), "name" : "小钱", "sex" : "男", "score1" : 89, "score2" : 36, "score3" : 102, "score5" : 65, "classID: " : 5 }
>

小于: 查询 socre1 小于80 的文档

> db.stu_info.find({"score1":{$lt:80}})
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0c"), "name" : "小李", "sex" : "女", "score1" : 53, "score2" : 91, "score3" : 34, "score5" : 19, "classID: " : 9 }
>



大于或等于:查询 socre3 大于等于 100 的文档

> db.stu_info.find({"score3":{$gte:100}})
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa09"), "name" : "小红", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 80, "classID: " : 3 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0b"), "name" : "小钱", "sex" : "男", "score1" : 89, "score2" : 36, "score3" : 102, "score5" : 65, "classID: " : 5 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0d"), "name" : "小王", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 99, "classID: " : 1 }
>


大于或等于:查询 socre1 小于等于 80 的文档

> db.stu_info.find({"score1":{$lte:80}})
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0a"), "name" : "小赵", "sex" : "女", "score1" : 80, "score2" : 79, "score3" : 33, "score5" : 55, "classID: " : 3 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0c"), "name" : "小李", "sex" : "女", "score1" : 53, "score2" : 91, "score3" : 34, "score5" : 19, "classID: " : 9 }
>


and | or 查询

and:查询 score1等于100 score2等于100 的文档

> db.stu_info.find({"score1":100,"score2":100})
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa09"), "name" : "小红", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 80, "classID: " : 3 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0d"), "name" : "小王", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 99, "classID: " : 1 }
>


**or: 查询socre1 等于 53 或者score2等于 94 的文档 **

> db.stu_info.find({$or:[{"score1":53},{"score2":94}]})
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0c"), "name" : "小李", "sex" : "女", "score1" : 53, "score2" : 91, "score3" : 34, "score5" : 19, "classID: " : 9 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0e"), "name" : "小周", "sex" : "女", "score1" : 99, "score2" : 94, "score3" : 92, "score5" : 90, "classID: " : 6 }
>



and 和 or 联合查询 :查询sex 等于 男  ,在此基础上 查询 score1 等于 99 或者  score1 等于 91 的文档

> db.stu_info.find({"sex":"女",$or:[{"score1":99},{"score2":91}]})
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0c"), "name" : "小李", "sex" : "女", "score1" : 53, "score2" : 91, "score3" : 34, "score5" : 19, "classID: " : 9 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0e"), "name" : "小周", "sex" : "女", "score1" : 99, "score2" : 94, "score3" : 92, "score5" : 90, "classID: " : 6 }
>



排序查询: 对score1进行升序和降序排序

1: 升序

-1: 降序

> db.stu_info.find().sort({"score1":1})
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0c"), "name" : "小李", "sex" : "女", "score1" : 53, "score2" : 91, "score3" : 34, "score5" : 19, "classID: " : 9 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0a"), "name" : "小赵", "sex" : "女", "score1" : 80, "score2" : 79, "score3" : 33, "score5" : 55, "classID: " : 3 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0b"), "name" : "小钱", "sex" : "男", "score1" : 89, "score2" : 36, "score3" : 102, "score5" : 65, "classID: " : 5 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa08"), "name" : "小明", "sex" : "男", "score1" : 98, "score2" : 60, "score3" : 79, "score5" : 101, "classID: " : 1 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0e"), "name" : "小周", "sex" : "女", "score1" : 99, "score2" : 94, "score3" : 92, "score5" : 90, "classID: " : 6 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa09"), "name" : "小红", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 80, "classID: " : 3 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0d"), "name" : "小王", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 99, "classID: " : 1 }
>
>  db.stu_info.find().sort({"score1":-1})
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa09"), "name" : "小红", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 80, "classID: " : 3 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0d"), "name" : "小王", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 99, "classID: " : 1 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0e"), "name" : "小周", "sex" : "女", "score1" : 99, "score2" : 94, "score3" : 92, "score5" : 90, "classID: " : 6 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa08"), "name" : "小明", "sex" : "男", "score1" : 98, "score2" : 60, "score3" : 79, "score5" : 101, "classID: " : 1 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0b"), "name" : "小钱", "sex" : "男", "score1" : 89, "score2" : 36, "score3" : 102, "score5" : 65, "classID: " : 5 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0a"), "name" : "小赵", "sex" : "女", "score1" : 80, "score2" : 79, "score3" : 33, "score5" : 55, "classID: " : 3 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0c"), "name" : "小李", "sex" : "女", "score1" : 53, "score2" : 91, "score3" : 34, "score5" : 19, "classID: " : 9 }
> 



指定返回域: 获取name 和 score1 域的数据

> db.stu_info.find({},{"name":1,"score1":1})
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa08"), "name" : "小明", "score1" : 98 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa09"), "name" : "小红", "score1" : 100 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0a"), "name" : "小赵", "score1" : 80 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0b"), "name" : "小钱", "score1" : 89 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0c"), "name" : "小李", "score1" : 53 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0d"), "name" : "小王", "score1" : 100 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0e"), "name" : "小周", "score1" : 99 }
> 

只返回一条:查询socre1小于等于100的数据,仅返回一条

> db.stu_info.findOne({"score1": {$lte: 100}})
{
        "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa08"),
        "name" : "小明",
        "sex" : "男",
        "score1" : 98,
        "score2" : 60,
        "score3" : 79,
        "score5" : 101,
        "classID: " : 1
}
>



只返回一条并且删除该数据:查询socre1小于等于100的数据,仅返回一条,并且删除

> db.stu_info.findOneAndDelete({"score1":{$lte:100}})
{
        "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa08"),
        "name" : "小明",
        "sex" : "男",
        "score1" : 98,
        "score2" : 60,
        "score3" : 79,
        "score5" : 101,
        "classID: " : 1
}
> db.stu_info.findOne({"name":"小明"})
null
>




4. 更新操作


4.1 用法

更新一个文档

db.CollectionName.updateOne()

更新多个文档

db.CollectionName.updateOne()

db.CollectionName.updateMany()


4.2 例子

只更新一个文档:将 score1 为 100 的文档 新增一个classID 为 16

> db.stu_info.find({"score1":100})
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa09"), "name" : "小红", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 80, "classID: " : 3 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0d"), "name" : "小王", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 99, "classID: " : 1 }
> 
> db.stu_info.updateOne({"score1":100},{$set:{"classID":16}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> 
> db.stu_info.find({"score1":100})
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa09"), "name" : "小红", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 80, "classID: " : 3, "classID" : 16 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0d"), "name" : "小王", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 99, "classID: " : 1 }
> 


更新多个文档

更新所有文档:将 score1 为 100 的文档 设置 新增/设置一个 classID 为 21

> db.stu_info.find({"score1":100})
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa09"), "name" : "小红", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 80, "classID: " : 3, "classID" : 16 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0d"), "name" : "小王", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 99, "classID: " : 1 }
> 
> db.stu_info.updateMany({"score1":100},{$set:{"classID":21}})
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
> 
> db.stu_info.find({"score1":100})
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa09"), "name" : "小红", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 80, "classID: " : 3, "classID" : 21 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0d"), "name" : "小王", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 99, "classID: " : 1, "classID" : 21 }
> 



5. 删除操作


5.1 用法

删除一条文档

db.CollectionName.deleteOne()


删除多条文档

db.CollectionName.deleteMany()


5.2 例子

删除一条文档:删除socre1为100的一条文档

> db.stu_info.find({"score1":100})
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa09"), "name" : "小红", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 80, "classID: " : 3, "classID" : 21 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0d"), "name" : "小王", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 99, "classID: " : 1, "classID" : 21 }
> 
> db.stu_info.deleteOne({"score1":100})
{ "acknowledged" : true, "deletedCount" : 1 }
> 
> db.stu_info.find({"score1":100})
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0d"), "name" : "小王", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 99, "classID: " : 1, "classID" : 21 }
>


删除多条文档: 删除socre1小于90的所有文档

> db.stu_info.find({"score1":{$lt:90}})
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0a"), "name" : "小赵", "sex" : "女", "score1" : 80, "score2" : 79, "score3" : 33, "score5" : 55, "classID: " : 3 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0b"), "name" : "小钱", "sex" : "男", "score1" : 89, "score2" : 36, "score3" : 102, "score5" : 65, "classID: " : 5 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0c"), "name" : "小李", "sex" : "女", "score1" : 53, "score2" : 91, "score3" : 34, "score5" : 19, "classID: " : 9 }
> 
> db.stu_info.deleteMany({"score1":{$lt:90}});
{ "acknowledged" : true, "deletedCount" : 3 }
> 
> db.stu_info.find({"score1":{$lt:90}})
>




6. 索引操作


6.1 用法


查询集合所有

db.CollectionName.getIndexes()

创建索引

db.CollectionName.createIndex()

删除集合除_id以外的所有索引

db.CollectionName.dropIndexes()

删除索引

db.CollectionName.dropIndex()


6.2 例子

查询集合所有


创建索引

语法

db.collection.createIndex(
  {
      "a": 1
  },
  {
      unique: true,
      sparse: true,
      expireAfterSeconds: 3600
  }
)


可选参数

background: bool类型  为true则在后台构建索引,默认为false
unique: bool类型  为true则创建唯一索引,默认为false
name: string类型  索引名称, 如果未指定,mongodb将通过索引字段和排序来生成索引名称
sparse: bool类型 为true则对文档不存在字段数据不启用索引,默认为false
expireAfterSeconds: 整形 指定一个值(以秒为单位)作为TTL,设置生存时间


例子1: 给集合stu_info sex name 增加唯一索引

> db.stu_info.getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "LearnDB.stu_info"
        }
]
> 
> db.stu_info.createIndex({"name":1} , {"background":true,"unique":true , "name":"stu_info_name"})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
> 
> db.stu_info.getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "LearnDB.stu_info"
        },
        {
                "v" : 2,
                "unique" : true,
                "key" : {
                        "name" : 1
                },
                "name" : "stu_info_name",
                "ns" : "LearnDB.stu_info",
                "background" : true
        }
]
>



尝试新增相同name的文档

> db.stu_info.find()
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0d"), "name" : "小王", "sex" : "女", "score1" : 100, "score2" : 100, "score3" : 100, "score5" : 99, "classID: " : 1, "classID" : 21 }
{ "_id" : ObjectId("61d6cac2a5a7b57ea8e0aa0e"), "name" : "小周", "sex" : "女", "score1" : 99, "score2" : 94, "score3" : 92, "score5" : 90, "classID: " : 6 }
> 
> db.stu_info.insertMany([     {"name": "小王" , "sex": "女" , "score1": 100 , "score2": 100, "score3": 100 , "score5": 99 , "classID: " : 1}     ])
2022-01-08T10:56:46.475+0800 E QUERY    [js] BulkWriteError: write error at item 0 in bulk operation :
BulkWriteError({
        "writeErrors" : [
                {
                        "index" : 0,
                        "code" : 11000,
                        "errmsg" : "E11000 duplicate key error collection: LearnDB.stu_info index: stu_info_name dup key: { : \"小王\" }",
                        "op" : {
                                "_id" : ObjectId("61d8fd6e3a0069c72ccea003"),
                                "name" : "小王",
                                "sex" : "女",
                                "score1" : 100,
                                "score2" : 100,
                                "score3" : 100,
                                "score5" : 99,
                                "classID: " : 1
                        }
                }
        ],
        "writeConcernErrors" : [ ],
        "nInserted" : 0,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})
BulkWriteError@src/mongo/shell/bulk_api.js:369:48
BulkWriteResult/this.toError@src/mongo/shell/bulk_api.js:333:24
Bulk/this.execute@src/mongo/shell/bulk_api.js:1173:1
DBCollection.prototype.insertMany@src/mongo/shell/crud_api.js:314:5
@(shell):1:1
>



删除索引:删除stu_info name 索引

> db.stu_info.getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "LearnDB.stu_info"
        },
        {
                "v" : 2,
                "unique" : true,
                "key" : {
                        "name" : 1
                },
                "name" : "stu_info_name",
                "ns" : "LearnDB.stu_info",
                "background" : true
        }
]
>
> db.stu_info.dropIndex("stu_info_name")
{ "nIndexesWas" : 2, "ok" : 1 }
>
> db.stu_info.getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "LearnDB.stu_info"
        }
]
>

相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
相关文章
|
NoSQL 数据可视化 关系型数据库
mongoDB入门教程三:数据库的创建和删除(增删改查)基本命令
mongoDB入门教程三:数据库的创建和删除(增删改查)基本命令
196 0
|
JSON NoSQL MongoDB
mongodb基本操作,增删改查,查询,索引,权限机制
mongodb基本操作,增删改查,查询,索引,权限机制
|
存储 NoSQL Java
SpringBoot 中使用 MongoDB 基于 MongoRepository增删改查(基础篇)
SpringBoot 中使用 MongoDB 基于 MongoRepository增删改查(基础篇)
590 0
|
4月前
|
SQL NoSQL API
MongoDB 增删改查 常用sql总结
MongoDB 增删改查 常用sql总结
162 1
|
5月前
|
NoSQL MongoDB 数据库
MongoDB的CURD(增删改查操作)
MongoDB的CURD(增删改查操作)
74 0
|
6月前
|
JSON NoSQL MongoDB
MongoDB【CRUD基本操作】
MongoDB【CRUD基本操作】
|
存储 JSON NoSQL
02 MongoDB - 基本操作
02 MongoDB - 基本操作
25 0
|
SQL NoSQL API
五分钟叫你学会操作MongoDB增删改查
五分钟叫你学会操作MongoDB增删改查
166 0
|
JSON NoSQL 数据库连接
[虚幻引擎 MongoDB Client 插件说明] DTMongoDB MongoDB数据库连接插件,UE蓝图可以操作MongoDB数据库增删改查。
本插件可以在UE里面使用蓝图操作MongoDB数据库, 对数据库进行查询,删除,插入,替换,更新操作。
207 0
|
20天前
|
NoSQL Cloud Native atlas
探索云原生数据库:MongoDB Atlas 的实践与思考
【10月更文挑战第21天】本文探讨了MongoDB Atlas的核心特性、实践应用及对云原生数据库未来的思考。MongoDB Atlas作为MongoDB的云原生版本,提供全球分布式、完全托管、弹性伸缩和安全合规等优势,支持快速部署、数据全球化、自动化运维和灵活定价。文章还讨论了云原生数据库的未来趋势,如架构灵活性、智能化运维和混合云支持,并分享了实施MongoDB Atlas的最佳实践。