MongoDB cmd CRUD操作 对照SQL

问题

参考官方文档
使用MogoDB 你就要熟悉他的常用cmd命令,增删改查,聚合多表查询等基本操作,本片博客旨在教会大家快速上手MogoDB,对其有基本了解,会对照Oracle的SQL查询
注:本篇文章主要目的是针对第一次接手mogodb数据库想快速上手的小伙伴,当然已经上手的可以当做个操作符查询文章来看,看完本篇文章,基本得CAUD,聚合,函数查询应该就没问题了(我会持续更新文章中的各种操作,力求变成一份学习文档)
需要什么功能查看全文后直接搜索,命名都是按照标准书写

C

查询是操作量最大的命令 此处罗列单表查询 聚合查询看目录

find

单表查询

db.UserInfo.find({})
   .projection({
   
   "ctime":"$ctime"})//输出指定字段,不写全部显示
   .sort({_id:-1})//指定字段排序 1正序 -1倒序
   .limit(100)//分页

简写查询

db.collection.find(query, projection)

返回符合条件的所有集合

db.Activity.find({
   
   "aId":"46aa3f07-f315-4651-b025-b6b16da44ee0"})

findOne

返回符合条件的一个集合

db.Activity.findOne({
   
   "aId":"46aa3f07-f315-4651-b025-b6b16da44ee0"})

R

新增

db.getCollection("StuRecord").insert({
    "flag": 0,
    "name": "test",
    "schoolId": "172b7e1d-78f8-42e7-b631-7f2cf4da8888",
    "stuNo": "1819149S1",
    "time": "2020-05-21 17:37:36.0"
})

U

更新一个

db.getCollection("StuRecord").update({ _id: ObjectId("5d5a6b29a0ed552270f8a87a") }, {
    $set: {
        "flag": 0,
        "name": "test",
        "schoolId": "172b7e1d-78f8-42e7-b631-7f2cf4da8888",
        "stuNo": "1819149S1",
        "time": "2020-05-21 17:37:36.0"
    }
})

批量更新

db.getCollection("DictionaryTable").updateMany({  "schoolId":"9af1edc5-3f02-46d4-b1b7-faf85fd3c9a4","type":22}, {
    $set: {
        "state": NumberInt(0),
    }
})

D

介绍

参考文章

命令 解释
db.collection.remove() Delete a single document or all documents that match a specified filter
db.collection.deleteOne() Delete at most a single document that match a specified filter even though multiple documents may match the specified filter.3.2 新版功能.
db.collection.deleteMany() 删除所有匹配指定过滤条件的文档.3.2 新版功能.

删除所有文档

要想从集合中删除所有文档,传递一个空的 filter document {} 给db.collection.deleteMany()db.collection.remove()方法. 无条件删除
该方法返回了操作状态的文档:

删除满足条件的所有文档

要想删除匹配删除条件的所有文档,传递 filter 参数给db.collection.deleteMany() 方法或 db.collection.remove() 方法.
例如:

db.Classes.remove({
   
   "schoolId":"56bb50a5-1441-4665-b368-9fc20efa8cd8"})
db.Classes.deleteMany({
   
   "schoolId":"56bb50a5-1441-4665-b368-9fc20efa8cd8"})

返回删除结果

{
	"acknowledged" : true,
	"deletedCount" : 2215
}

多表关联删除 批量删除

一对多关系中删除,可以通过条件循环删除
y相当于变量,代表当前文档对象

db.UserInfo.find({
   
   "schoolId":"20c5010a-e096-4c54-83be-61a9e35de69c"}).forEach(
     function(y){
      db.Account.remove({
   
   "userId" :y.uid});
    //   print(y);
     }
);

多表关联新增 批量新增备份

 db.TraineeVisit.find({ time: { $gte: "2019-07-01" }}).forEach(
     function(y){
      db.TraineeVisitHistory.insert({y});
    //   print(y);
     }
);

操作符

条件操作符

$eq等于

db.Role.find({
   
   "schoolId" : {$eq:"4e98f1bc-3ad5-4f41-9969-39d10a022597"}})
db.Role.find({
   
   "type" : {$eq:1}})

$ne 不等于

db.Activity.find({
   
   "end":{$ne:1596211199000}})

sql

	where end!= 50

$lt小于

db.Activity.find({
   
   "start":{$lt:1596211199000} })

sql

where start< 50

$lte小于等于

db.Activity.find({
   
   "start":{$lte:1596211199000} })

sql

where start<= 50

$gt大于

db.Activity.find({
   
   "end":{$gt:1596211199000} })

sql

where end> 50

$gte大于等于

db.Activity.find({
   
   "end":{$gte:1596211199000}}) 

sql

where end>= 50

$regex 模糊查询

db.Student.find({
   
   "county":{$regex:"顺德"}})
SELECT * FROM Student where name like "李%"

$exists 存在字段

查询该字段存在与集合中 但是存在不保证为空

//存在
db.ExcelOperation.find({
   
   "founder":{$exists:true}})
//不存在
db.ExcelOperation.find({
   
   "founder":{$exists:false}})

$ifNull 存在且不为null

当前字段存在且不为null 就会返回参数12(参数可以多种),类似三元表达式

db.ExcelOperation.aggregate([
    {
        $project: {
             "founder": { $ifNull: [true, false] },
             "state": { $ifNull: [1, 2] },
        }
    }
])

$cond if-else

语法中写操作符,返回一个布尔值,依据布尔值决定赋值于字段,then为true else为false,适用于聚合

db.ExcelOperation.aggregate([
    {
        $project: {
            "dormitoryId": {
                $cond: {
                    if: {
                      $eq: ["$state", 5]
                    },
                    then: 1,
                    else: 0
                }

            },
        }
    }
])

时间区间

注:时间字符串类型可以直接比较,不用转换,包括存储为字符串类型时间

db.Activity.find({
   
   "startTime":{$lte:"2020-07-21 23:59:59"},"endTime":{$gte:"2020-07-21 23:59:59"} })

聚合

聚合多表查询

一对多,一对一

主表

当前语句相当于查询所有

db.StuRecord.aggregate([

])

主表关联B表

db.StuRecord.aggregate([//A表
    {
        $lookup: {
            from: "Student",//表
            localField: "stuNo",//A表表内部字段与B对应字段
            foreignField: "stuNo",//B表内部字段
            as: "stu"//对象代替
        }
    },
    { $unwind: '$stu' },//一对一
])

查询结果,A表全显B表对象形式显示
在这里插入图片描述

查询条件

条件可以写多个,B表需要使用对象调用

db.StuRecord.aggregate([//A表
    {
        $lookup: {
            from: "Student",//表
            localField: "stuNo",//A表表内部字段与B对应字段
            foreignField: "stuNo",//B表内部字段
            as: "stu"//对象代替
        }
    },
    { $unwind: '$stu' },//一对一
    {
        $match: {
            "time": { $gte: "2020-07-10 00:00:00.0", $lte: "2020-07-10 23:59:59.9" },//A表条件
            "stu.classId": "1cb54339-4e9c-4b8a-a35c-94f87f9663c0",//B表条件
        }
    },
])

在这里插入图片描述

输出指定参数

db.StuRecord.aggregate([//A表
    {
        $lookup: {
            from: "Student",//表
            localField: "stuNo",//A表表内部字段与B对应字段
            foreignField: "stuNo",//B表内部字段
            as: "stu"//对象代替
        }
    },
    { $unwind: '$stu' },//一对一
    {
        $match: {
            "time": { $gte: "2020-07-10 00:00:00.0", $lte: "2020-07-10 23:59:59.9" },//A表条件
            "stu.classId": "1cb54339-4e9c-4b8a-a35c-94f87f9663c0",//B表条件
        }
    },
    {
        $project: {
            "stuNo": "$stuNo",//输出指定字段
            "classId": "$stu.classId",//输出指定字段,B表的需要对象调用
            "isTime": {
                $cond: {
   
   //if判断写法
                    if: {
                        $gt: ["$time", "2020-07-10 07:52:00"],
                    },
                    then: 1,
                    else: 0
                }
            }
        }
    },
])

在这里插入图片描述

分组


db.StuRecord.aggregate([//A表
    {
        $lookup: {
            from: "Student",//表
            localField: "stuNo",//A表表内部字段与B对应字段
            foreignField: "stuNo",//B表内部字段
            as: "stu"//对象代替
        }
    },
    { $unwind: '$stu' },//一对一
    {
        $match: {
            "time": { $gte: "2020-07-10 00:00:00.0", $lte: "2020-07-10 23:59:59.9" },//A表条件
            "stu.classId": "1cb54339-4e9c-4b8a-a35c-94f87f9663c0",//B表条件
        }
    },
    {
        $project: {
            "stuNo": "$stuNo",//输出指定字段
            "classId": "$stu.classId",//输出指定字段,B表的需要对象调用
            "isTime": {
                $cond: {
   
   //if判断写法
                    if: {
                        $gt: ["$time", "2020-07-10 07:52:00"],
                    },
                    then: 1,
                    else: 0
                }
            }
        }
    },
    {
        $group: {
            _id: "$stuNo",//需要分组字段
            "isTime": { $push: "$$ROOT.isTime" },//$$ROOT 获取当前分组文档,可以查看组内文档
            "time": { $push: "$$ROOT.time" },
            "classId": { $push: "$$ROOT.classId" },

        }
    },
])

在这里插入图片描述

排序

排序有顺序,分组后还是分组前

db.StuRecord.aggregate([//A表
    {
        $lookup: {
            from: "Student",//表
            localField: "stuNo",//A表表内部字段与B对应字段
            foreignField: "stuNo",//B表内部字段
            as: "stu"//对象代替
        }
    },
    { $unwind: '$stu' },//一对一
    {
        $match: {
            "time": { $gte: "2020-07-10 00:00:00.0", $lte: "2020-07-10 23:59:59.9" },//A表条件
            "stu.classId": "1cb54339-4e9c-4b8a-a35c-94f87f9663c0",//B表条件
        }
    },
    {
        $project: {
            "stuNo": "$stuNo",//输出指定字段
            "classId": "$stu.classId",//输出指定字段,B表的需要对象调用
            "time":"$time",
            "isTime": {
                $cond: {
   
   //if判断写法
                    if: {
                        $gt: ["$time", "2020-07-10 07:52:00"],
                    },
                    then: 1,
                    else: 0
                }
            }
        }
    },
    {
        $group: {
            _id: "$stuNo",//需要分组字段
            "isTime": { $push: "$$ROOT.isTime" },//$$ROOT 获取当前分组文档,可以查看组内文档
            // "time": { $push: "$$ROOT.time" },
            "classId": { $push: "$$ROOT.classId" },

        }
    },
    {
        $sort: {
            time: 1//排序 1为升序,-1为降序
        }
    },
])

在这里插入图片描述

索引

添加索引

语法中 Key 值为你要创建的索引字段,1 为指定按升序创建索引,如果你想按降序来创建索引指定为 -1 即可。

 db.collection.createIndex(keys, options)
  db.Student.createIndex({
   
   "sid":1})

多个索引

createIndex() 方法中你也可以设置使用多个字段创建索引(关系型数据库中称作复合索引)。

db.col.createIndex({
   
   "title":1,"description":-1})

在这里插入图片描述

查看索引

可以查看当前集合的所有索引

db.col.getIndexes()

查看索引大小

 db.col.totalIndexSize()

删除索引

db.col.dropIndexes()

删除指定索引

db.col.dropIndex("索引名称")

参考文章

去重

函数

排序 sort

key为排序字段,1为正序,-1为倒序

db.COLLECTION_NAME.find().sort({
   
   KEY:1})

猜你喜欢

转载自blog.csdn.net/HezhezhiyuLe/article/details/106868281