一、Mongodb数据库介绍

1.Mongodb简介

MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,
最像关系数据库的,它是一个面向集合的,模式自由的文档型数据库。

2.Mongodb适用场景

MongoDB是一个基于分布式文件存储的数据库。由C++语言编写,旨在为WEB应用提供可扩展的高性能数据存储解决方案。

3.MongoDB特性

  • 面向集合存储,易于存储对象类型的数据。
  • 模式自由
  • 支持动态查询
  • 支持完全索引,包含内部对象
  • 支持复制和故障恢复
  • 使用高效的二进制数据存储,包括大型对象(如视频等)
  • 自动处理碎片,以支持云计算层次的扩展性
  • 文件存储格式为BSON(一种JSON的扩展

二、检查本地系统环境

1.检查系统版本

[root@xbs ~]# cat /etc/os-release
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"

CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"

2.检查yum仓库

[root@xbs ~]# yum repolist all
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
repo id                                             repo name                                                                              status
base/7/x86_64                                       CentOS-7 - Base - mirrors.aliyun.com                                                   enabled: 10,072
centosplus/7/x86_64                                 CentOS-7 - Plus - mirrors.aliyun.com                                                   disabled
contrib/7/x86_64                                    CentOS-7 - Contrib - mirrors.aliyun.com                                                disabled
epel/x86_64                                         Extra Packages for Enterprise Linux 7 - x86_64                                         enabled: 13,759
epel-debuginfo/x86_64                               Extra Packages for Enterprise Linux 7 - x86_64 - Debug                                 disabled
epel-source                                         Extra Packages for Enterprise Linux 7 - x86_64 - Source                                disabled
extras/7/x86_64                                     CentOS-7 - Extras - mirrors.aliyun.com                                                 enabled:    518
nginx-stable/7/x86_64                               nginx stable repo                                                                      enabled:    318
updates/7/x86_64                                    CentOS-7 - Updates - mirrors.aliyun.com                                                enabled:  5,061
repolist: 29,728

三、Mongodb的安装

1.配置Mongodb的yum源

#添加yum源
[root@xbs ~]# vim /etc/yum.repos.d/mongodb.repo
[root@xbs ~]# cat /etc/yum.repos.d/mongodb.repo
[mongodb-org]
name=MongoDB Repository
baseurl=https://mirrors.tuna.tsinghua.edu.cn/mongodb/yum/el$releasever/
gpgcheck=0
enabled=1
#清除yum缓存 重新加载
[root@xbs ~]# yum clean all && yum makecache

2.安装Mongodb

[root@xbs ~]# yum install -y mongodb-org-server mongodb-org

3.修改绑定IP

[root@xbs ~]# sed -i 's#bindIp: 127.0.0.1#bindIp: 0.0.0.0#g' /etc/mongod.conf 
[root@xbs ~]# grep bind /etc/mongod.conf 
  bindIp: 0.0.0.0  # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.

4.启动Mongodb服务

[root@xbs ~]# systemctl start mongod.service
[root@xbs ~]# systemctl enable  mongod.service

四、检查Mongodb状态

1.查看Mongodb服务状态

[root@xbs ~]# systemctl status  mongod.service
● mongod.service - MongoDB Database Server
   Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)
   Active: active (running) since Sun 2023-08-06 13:07:11 CST; 1min 11s ago
     Docs: https://docs.mongodb.org/manual
 Main PID: 10066 (mongod)
   CGroup: /system.slice/mongod.service
           └─10066 /usr/bin/mongod -f /etc/mongod.conf

Aug 06 13:07:11 xbs systemd[1]: Started MongoDB Database Server.
Aug 06 13:07:11 xbs mongod[10066]: {"t":{"$date":"2023-08-06T05:07:11.335Z"},"s":"I",  "c":"CONTROL",  "id":7484500, "ctx":"-","msg":"Environm...o false"}
Hint: Some lines were ellipsized, use -l to show in full.

2.检查Mongodb服务端口

[root@xbs ~]# netstat -tunlp |grep 27017
tcp        0      0 0.0.0.0:27017           0.0.0.0:*               LISTEN      10066/mongod  

3.检查Mongodb版本

[root@xbs ~]# mongo  --version
MongoDB shell version v5.0.19
Build Info: {
    "version": "5.0.19",
    "gitVersion": "0736b66d8cf64847cbd71c5472b0d6f19b1f5daa",
    "openSSLVersion": "OpenSSL 1.0.1e-fips 11 Feb 2013",
    "modules": [],
    "allocator": "tcmalloc",
    "environment": {
        "distmod": "rhel70",
        "distarch": "x86_64",
        "target_arch": "x86_64"
    }
}

五、连接Mongodb

1.本地连接Mongodb数据库

[root@xbs ~]# mongo
MongoDB shell version v5.0.19
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("0450091b-f019-43c8-bbce-621591a8b65c") }
MongoDB server version: 5.0.19
================
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/
================
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
        https://docs.mongodb.com/
Questions? Try the MongoDB Developer Community Forums
        https://community.mongodb.com
---
The server generated these startup warnings when booting: 
        2023-08-06T13:07:12.183+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
        2023-08-06T13:07:12.183+08:00: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. We suggest setting it to 'never'
        2023-08-06T13:07:12.183+08:00: /sys/kernel/mm/transparent_hugepage/defrag is 'always'. We suggest setting it to 'never'
---
> 

2.查看默认数据库

  • admin: 从权限的角度来看,这是"root"数据库。超级管理员的库,存储用户信息。
  • local:这个数据永远不会被复制,可以用来存储限于本地单台服务器的任意集合。
  • config: 当Mongo用于分片设置时,config数据库在内部使用,用于保存分片的相关信息。
> show dbs;
admin   0.000GB
config  0.000GB
local   0.000GB

六、Mongodb数据库的基本操作

1.创建一个数据库

> use test;       #//如果数据库不存在,则创建并切换到该数据库,存在则切换到该数据库
switched to db test
> show dbs;               #//创建的 test数据库并没有显示,需要插入数据才能显示
admin   0.000GB
config  0.000GB
local   0.000GB
> db.class.insert({ "name": "王岑卿", "age": "18", "genden": "female" });
> show dbs;
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB

2.进入某个数据库

> use test
switched to db test

3.向数据库中插入数据

db.class.insert({ "name": "王岑卿", "age": "18", "genden": "female" });

4.查看数据库列表

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

5.查询表中数据

> db.class.find();          #//需要进入相应的数据库里查看
{ "_id" : ObjectId("64cf2c66654e859e97dd2cbf"), "name" : "王笑笑", "age" : "18", "genden" : "female" }
{ "_id" : ObjectId("64cf2c97654e859e97dd2cc0"), "name" : "王岑卿", "age" : "18", "genden" : "female" }

6.删除数据库

> use test;
switched to db test
> db.dropDatabase();
{ "ok" : 1 }

7.创建单个表

> use test;
switched to db test
> db.createCollection("t1")
{ "ok" : 1 }

8.删除单个表

> show tables;
t1
> db.t1.drop()
true
> show tables;

七、Mongodb数据的增删查改

1.向集合中插入文档数据——增

> db.mall.insert({  "type":  "phone",  "price":  "3799","xinghao":  "huawei", "desc":  "abbbb" })
WriteResult({ "nInserted" : 1 })

2.查找数据——查

①查找一个表所有数据

> db.t1.find()
{ "_id" : ObjectId("64cf301a654e859e97dd2cc5"), "name" : "王笑笑", "age" : "18", "genden" : "female" }
{ "_id" : ObjectId("64cf3022654e859e97dd2cc6"), "name" : "王岑卿", "age" : "18", "genden" : "female" }

②查询单个文档数据

> db.t1.find({"name" : "王笑笑"})
{ "_id" : ObjectId("64cf301a654e859e97dd2cc5"), "name" : "王笑笑", "age" : "18", "genden" : "female" }

③查看集合内容,以固定格式显示

> db.t1.find().pretty();
{
        "_id" : ObjectId("64cf301a654e859e97dd2cc5"),
        "name" : "王笑笑",
        "age" : "18",
        "genden" : "female"
}
{
        "_id" : ObjectId("64cf3022654e859e97dd2cc6"),
        "name" : "王岑卿",
        "age" : "18",
        "genden" : "female"
}

3.更改数据——改

①更新集合中文档数据

> db.mall.find().pretty();
{
        "_id" : ObjectId("64cf30d2654e859e97dd2cc7"),
        "type" : "phone",
        "price" : "3799",
        "xinghao" : "huawei",
        "desc" : "abbbb"
}
#修改phone为TV
> db.mall.updateMany({ "type": "phone" }, { $set: { "type": "TV" } });
> db.mall.find().pretty();
{
        "_id" : ObjectId("64cf30d2654e859e97dd2cc7"),
        "type" : "TV",
        "price" : "3799",
        "xinghao" : "huawei",
        "desc" : "abbbb"
}

4.删除数据——删

deleteOne(filter):这个方法用于删除符合指定条件 filter 的第一条匹配的文档。
deleteMany(filter):这个方法用于删除符合指定条件 filter 的所有匹配的文档

> db.t1.find()
{ "_id" : ObjectId("64cf301a654e859e97dd2cc5"), "name" : "王笑笑", "age" : "18", "genden" : "female" }
{ "_id" : ObjectId("64cf3022654e859e97dd2cc6"), "name" : "王岑卿", "age" : "18", "genden" : "female" }
> db.t1.deleteOne({"age": "18"})
{ "acknowledged" : true, "deletedCount" : 1 }
> db.t1.find({"age": "18"})
{ "_id" : ObjectId("64cf3022654e859e97dd2cc6"), "name" : "王岑卿", "age" : "18", "genden" : "female" }