MongoDB

简介

NoSQL(NoSQL = Not Only SQL ),意即”不仅仅是SQL”

MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统。

在高负载的情况下,添加更多的节点,可以保证服务器性能。

MongoDB 旨在为WEB应用提供可扩展的高性能数据存储解决方案。

MongoDB 将数据存储为一个文档,数据结构由键值(key=>value)对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组。

相关网站

官网手册 👉 https://www.mongodb.com/docs/manual/tutorial/getting-started/

中文手册 👉 https://mongodb.net.cn/manual/

菜鸟教程 👉 https://www.runoob.com/mongodb/mongodb-databases-documents-collections.html

Docker安装

# 拉取镜像
docker pull mongo

# 创建容器
docker run -d -p 27017:27017 -v mongo_configdb:/data/configdb -v mongo_db:/data/db --name mongo-test mongo --auth

# 进入容器
docker exec -it mongo-test mongo admin

# 创建管理员账号
db.createUser({ user: 'username', pwd: 'password', roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] });
# 创建root账号
db.createUser({user: 'root', pwd: 'root', roles: ['root']})

MongoDB 概念解析

SQL术语/概念 MongoDB术语/概念 解释/说明
database database 数据库
table collection 数据库表/集合
row document 数据记录行/文档
column field 数据字段/域
index index 索引
table joins 嵌套文档 表连接,MongoDB不支持,使用嵌入式的文档来代替关联查询
primary key primary key 主键,MongoDB自动将_id字段设置为主键

设计规范

  1. 数据库设计规范
    1. 数据库名约定小写
    2. 不能包含除 _ 以外的特殊字符
    3. 长度最大为64个字符
  2. 集合设计规范
    1. 集合名称约定小写
    2. 不能包含除 _ 以外的特殊字符,禁止以 system. 开头
    3. 长度最大为64个字符,包含前缀 database. 的内容
    4. 同一个业务尽可能使用相同前缀,尽可能表达用途,【业务标识】_【表标识】
  3. 文档设计规范
    1. KEY 不能以$开头,不能包含.(点号)
    2. _ID 推荐默认值,自定义主键会减慢插入速度
    3. 推荐使用短字段名,为了提高查询效率,应尽量在统一了大小写之后再插入到数据库中
    4. 禁止在同一个集合字段中存储多个数据类型的数据
    5. 禁止日期类型选择为string,不同的日期格式的文档,不支持等值查询,不支持范围查询
    6. 建议尽量不要存储大型对象,MongoDB能够支持最大16 MB的文档大小
  4. 索引设计规范
    1. 索引命名:IDX_【索引字段名】
    2. 长度不超128个字符
    3. 遵循“最左原则”

常用命令

  • 基本指令

    # 显示数据库
    show dbs
    show databases
    
    # 进入指定数据库
    use 数据库名称
    
    # 查看当前所在数据库
    db
    
    # 显示数据库中所有集合
    show collections
  • CRUD操作

    • # 增一条
      db.student_info.insertOne({
          name: 'zhangsan',
          age: 9,
          gender: 'male',
          hobby: ['sing', 'jump', 'rap', 'basketball'],
          exam_score: [
              {
                  'yu': 5
              },
              {
                  'shu': 2
              },
              {
                  'wai': 3
              }
          ]
      })
      
      # 增多条
      db.student_info.insertMany([{
          name: 'lisi',
          age: 13,
          gender: 'famale',
          hobby: ['basketball', 'football'],
          exam_score: [{
              'yu': 90
          }, {
              'shu': 96
          }, {
              'wai': 89
          }],
          is_famale: true
      }, {
          name: 'wangwu',
          age: 7,
          gender: 'male',
          hobby: ['sleep', 'eat'],
          exam_score: [{
              'yu': 55
          }, {
              'shu': 20
          }, {
              'wai': 93
          }]
      }, {
          name: 'zhaoliu',
          age: 16,
          gender: 'male',
          hobby: ['study', 'play'],
          exam_score: [{
              'yu': 100
          }, {
              'shu': 100
          }, {
              'wai': 100
          }]
      }])
      
      # 不推荐直接使用 insert()
      
      # 插入的其他方法
      db.collection.updateOne() # 与upsert: true选项一起使用时。
      db.collection.updateMany() # 与upsert: true选项一起使用时。
      db.collection.findAndModify() # 与upsert: true选项一起使用时。
      db.collection.findOneAndUpdate()# 与 upsert: true选项一起使用时。
      db.collection.findOneAndReplace()# 与 upsert: true选项一起使用时。
      
    • # 查询表中所有的数据
      db.student_info.find()
      db.getCollection("student_info").find()
      
      # 查第一条
      db.student_info.findOne()
      db.student_info.find().limit(1)
      
      # 查总数
      db.student_info.find().count()
      db.student_info.find().length()
      
      
      # 查询 age=13 的数据
      db.student_info.find({
          age: 13
      })
      
      # 查询 age=13 的数据 只返回 name、gender 字段
      db.student_info.find({
          age: 13
      }, {
          _id: 0,
          name: 1,
          gender: 1
      })
      
      # 查询 10<age≤16 的数据
      db.student_info.find({
          $and: [
              {
                  age: {
                      $gt: 10
                  }
              },
              {
                  age: {
                      $lte: 16
                  }
              }
          ]
      })
      
      db.student_info.find({
          age: {
              $gt: 10,
              $lte: 16
          }
      })
      
      # 常用的比较运算符:
      # $gt: 大于   $lt: 小于
      # $gte: 大于等于   $lte:小于等于
      # $ne: 不等于
      
      # 查询后,排序 (升序 1,降序 -1)
      db.student_info.find({
          age: {
              $gt: 0,
              $lte: 20
          }
      }).sort({
          age:  - 1
      })
      
      # limit()方法来读取指定数量的数据,skip()方法来跳过指定数量的数据
      db.student_info.find().limit(3).skip(2)
      
      # 是否存在 is_famale 字段
      db.student_info.find({
          is_famale: {
              $exists: true
          }
      })
      
      # 正则匹配
      db.student_info.find({
          name: {
              $regex: /^zhang. * /
          }
      })
      
      
      
      
      
    • # name = zhangsan 的数据,zhangsan 改成 kuangtuzhangsan
      db.student_info.updateOne(
          {
              name: 'zhangsan'
          },
          {
              $set: {
                  name: 'kuangtuzhangsan'
              }
          }
      )
      
      # gender = male 新增字段  new_field = '新增字段'
      db.student_info.updateMany(
          {
              gender: 'male'
          },
          {
              $set: {
                  new_field: '新增字段'
              }
          }
      )
      
      # 用更新语句删除 new_field 字段
      db.student_info.updateMany(
          {
              gender: 'male'
          },
          {
              $unset: {
                  new_field: true
              }
          }
      )
    • # 删除一条 name = "kuangtuzhangsan"
      db.student_info.deleteOne({
          name: "kuangtuzhangsan"
      })
      
      # 删除多条 10<age≤16 的数据
      db.student_info.deleteMany({
          age: {
              $gt: 10,
              $lte: 16
          }
      })
      
      # 删除全部数据
      db.student_info.deleteMany({})
      
      # 删除集合
      db.student_info.drop()
      
      # 删除数据库
      db.dropDatabase()

Java 操作

SpringBoot MongoTemplate
https://www.mongodb.com/java

Python 操作

motor
pymongo

MongoDB
https://元气码农少女酱.我爱你/7ebbaebed260/
作者
元气码农少女酱
发布于
2023年5月2日
许可协议