锐单电子商城 , 一站式电子元器件采购平台!
  • 电话:400-990-0325

MongoDB

时间:2023-08-04 04:37:00 56asc532连接器

MongoDB

[外链图片存储失败,源站可能有防盗链机制,建议保存图片直接上传(img-ak70Ne1J-1652786798071)(MongoDB.assets/1652526836510.png)]

特点

特点

  • 集合存储容易存储对象类型的数据
  • 支持查询和动态查询
  • 支持RUBY,PYTHON,JAMA,C ,PHP,C#等多种语言
  • 文件存储格式为BSON(一种JSON的扩展)
  • 支持复制和故障恢复和分片
  • 支持事务支持
  • 索引、聚合、关联…

应用场景

  • 游戏应用:使用云数据库MongoDB用户信息作为游戏服务器的数据库存储。用户的游戏设备和积分直接以嵌入式文档的形式存储,便于查询和更新。
  • 物流应用:使用云数据库MongoDB以云数据库存储订单信息,在运输过程中不断更新订单状态MongoDB以嵌入式数组的形式存储,一次查询即可读取订单的所有变更,方便快捷,一目了然。
  • 社交应用:使用云数据库MongoDB通过地理位置索引,存储用户信息和用户发布的朋友圈信息,实现附近的人、地点等功能。此外,云数据库MongoDB由于常适合存储聊天记录,因为它提供了非常丰富的查询,并且在写入和阅读方面相对较快。
  • 视频直播:使用云数据库MongoDB存储用户信息、礼品信息等。
  • 大数据应用:使用云数据库MongoDB云存储系统作为大数据,随时进行数据提取分析,掌握行业动态。

安装

传统方式

下载连接: Try MongoDB Atlas Products | MongoDB

[外链图片存储失败,源站可能有防盗链机制,建议保存图片直接上传(img-UP0nhmXn-1652786798072)(MongoDB.assets/1652535978224.png)]

[外链图片存储失败,源站可能有防盗链机制,建议保存图片直接上传(img-JiST8VsN-1652786798073)(MongoDB.assets/1652536005323.png)]

[外链图片存储失败,源站可能有防盗链机制,建议保存图片直接上传(img-zyxQe8QJ-1652786798073)(MongoDB.assets/1652536078235.png)]

解压:

[root@root mongoDB]# ls mongodb-linux-x86_64-rhel70-5.0.8.tgz [root@root mongoDB]# tar -zxf mongodb-linux-x86_64-rhel70-5.0.8.tgz # 解压 [root@root mongoDB]# ls mongodb-linux-x86_64-rhel70-5.0.8  mongodb-linux-x86_64-rhel70-5.0.8.tgz [root@root mongoDB]# mv mongodb-linux-x86_64-rhel70-5.0.8 mongodb # 改名 [root@root mongoDB]# ls mongodb  mongodb-linux-x86_64-rhel70-5.0.8.tgz [root@root mongoDB]#   

查看目录中的信息

[root@root mongoDB]# cd mongodb/ [root@root mongodb]# ls bin  LICENSE-Community.txt  MPL-2  README  THIRD-PARTY-NOTICES [root@root mongodb]# ll 总用量 132 drwxr-xr-x. 2 root root    70 514 09:48 bin -rw-r--r--. 1 root root 30608 421 17:15 LICENSE-Community.tx
-rw-r--r--. 1 root root 16726 421 17:15 MPL-2
-rw-r--r--. 1 root root  1977 421 17:15 README
-rw-r--r--. 1 root root 76823 421 17:15 THIRD-PARTY-NOTICES
[root@root mongodb]# cd bin/
[root@root bin]# ls
install_compass  mongo  mongod  mongos
[root@root bin]# ll
总用量 238632
-rwxr-xr-x. 1 root root     15205 421 17:15 install_compass
-rwxr-xr-x. 1 root root  58460872 421 18:01 mongo
-rwxr-xr-x. 1 root root 109480888 421 18:02 mongod
-rwxr-xr-x. 1 root root  76396488 421 17:40 mongos

启动MongoDB

# 上一级目录创建 data与logs文件夹
[root@root bin]# mkdir ../data
[root@root bin]# mkdir ../logs
[root@root bin]# ls ..
bin  data  LICENSE-Community.txt  logs  MPL-2  README  THIRD-PARTY-NOTICES
 # 当前目录下的mongod 端口号27017 存储文件的位置 上一级的data 存日志的目录上一级的logs下的mongo.log
 # 文件
 ./mongod --port=27017 --dbpath=../data --logpath=../logs/mongo.log

查看是否开启成功

[root@root bin]# ./mongo --port=27017
MongoDB shell version v5.0.8
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { 
         "id" : UUID("e7163a03-f323-4148-b616-a0894230e671") }
MongoDB server version: 5.0.8
================
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: 
        2022-05-14T10:11:28.080-04:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
        2022-05-14T10:11:28.080-04:00: You are running this process as the root user, which is not recommended
        2022-05-14T10:11:28.080-04:00: This server is bound to localhost. Remote systems will be unable to connect to this server. Start the server with --bind_ip <address> to specify which IP addresses it should serve responses from, or with --bind_ip_all to bind to all interfaces. If this behavior is desired, start the server with --bind_ip 127.0.0.1 to disable this warning
        2022-05-14T10:11:28.080-04:00: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. We suggest setting it to 'never'
        2022-05-14T10:11:28.080-04:00: /sys/kernel/mm/transparent_hugepage/defrag is 'always'. We suggest setting it to 'never'
        2022-05-14T10:11:28.080-04:00: Soft rlimits for open file descriptors too low
        2022-05-14T10:11:28.080-04:00:         currentValue: 1024
        2022-05-14T10:11:28.080-04:00:         recommendedMinimum: 64000
---
---
        Enable MongoDB's free cloud-based monitoring service, which will then receive and display
        metrics about your deployment (disk utilization, CPU, operation statistics, etc).

        The monitoring data will be available on a MongoDB website with a unique URL accessible to you
        and anyone you share the URL with. MongoDB may use this information to make product
        improvements and to suggest MongoDB products and deployment options to you.

        To enable free monitoring, run the following command: db.enableFreeMonitoring()
        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
> show dbs;  # 输入show bds; 如果出现下面的信息则表示成功
admin   0.000GB
config  0.000GB
local   0.000GB
> 

docker版:

sudo systemctl start docker # 开启docker 服务
docker pull mongo:5.0.8 # 拉取mongo5.0.8
docker run --name mongo -d -p 27017:27017 mongo:5.0.8 # 后台运行

查看运行状态:

[root@root bin]# docker ps
CONTAINER ID   IMAGE         COMMAND                  CREATED         STATUS         PORTS                                           NAMES
efd8986d6ee8   mongo:5.0.8   "docker-entrypoint.s…"   9 seconds ago   Up 8 seconds   0.0.0.0:27017->27017/tcp, :::27017->27017/tcp   mongo
[root@root bin]# 

进入容器内部:

[root@root bin]# docker exec -it efd8986d6ee8 bash
root@efd8986d6ee8:/# mongo
MongoDB shell version v5.0.8
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
{ 
        "t":{ 
        "$date":"2022-05-14T15:02:55.808Z"},"s":"I",  "c":"NETWORK",  "id":5693100, "ctx":"js","msg":"Asio socket.set_option failed with std::system_error","attr":{ 
        "note":"connect (sync) TCP fast open","option":{ 
        "level":6,"name":30,"data":"01 00 00 00"},"error":{ 
        "what":"set_option: Protocol not available","message":"Protocol not available","category":"asio.system","value":92}}}
Implicit session: session { 
         "id" : UUID("bdead5f3-d99c-45f8-a065-c6f020e99063") }
MongoDB server version: 5.0.8
================
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: 
        2022-05-14T14:56:02.063+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
        2022-05-14T14:56:02.063+00:00: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. We suggest setting it to 'never'
        2022-05-14T14:56:02.063+00:00: /sys/kernel/mm/transparent_hugepage/defrag is 'always'. We suggest setting it to 'never'
---
---
        Enable MongoDB's free cloud-based monitoring service, which will then receive and display
        metrics about your deployment (disk utilization, CPU, operation statistics, etc).

        The monitoring data will be available on a MongoDB website with a unique URL accessible to you
        and anyone you share the URL with. MongoDB may use this information to make product
        improvements and to suggest MongoDB products and deployment options to you.

        To enable free monitoring, run the following command: db.enableFreeMonitoring()
        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
> 

输入show dbs;

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> 
# ok 运行成功

停止服务:

docker stop efd8986d6ee8

核心概念

==mongodb中的库就类似于传统关系型数据库中库的概念,用来通过不同库隔离不同应用数据。==mongodb中可以建立多个数据库。每一个库都有自己的集合和权限,不同的数据库也放置在不同的文件中。默认的数据库为"test",数据库存储在启动指定的data目录中。

集合

集合就是MongoDB文档组,类似于RDBMS(关系数据库管理系统: RelationalDatabase Management System)中的表的概念。
集合存在于数据库中,一个库中可以创建多个集合。每个集合没有固定的结构,这意味着你在对集合可以插入不同格式和类型的数据,但通常情况下我们插入集合的数据都会有一定的关联性。

文档

文档集合中一条条记录,是一组键值(key-value)对(即BSON)。MongoDB的文档不需要设置相同的字段,并且相同的字段不需要相同的数据类型,这与关系型数据库有很大的区别,也是MongoDB非常突出的特点。

一个简单的文档例子如下:

{ 
         "site" : "li" , "name":"li"}

关系总结

RDBMS MongoDB
数据库 数据库
集合
文档
字段

基本操作

  • 查看所有库
> show databases; | show dbs;

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dtLZglPJ-1652786798074)(MongoDB.assets/1652586519809.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fkcybR2Q-1652786798075)(MongoDB.assets/1652586590882.png)]

注意:

  • admin: 从权限的角度来看,这是""root"数据库。要是将一个用户添加到这个数据库,这个用户自动继承所有数据库的权限。一些特定的服务器端命令也只能从这个数据库运行,比如列出所有的数据库或者关闭服务
  • local : 这个数据永远不会被复制,可以用来存储限于本地单台服务器的任意集合
  • config : 当Mongo用于分片设置时,config数据库在内部使用,用于保存分片的相关信息。
  • 创建数据库
> use 库名 # 如果没有这个数据库则创建有这个数据库则切换到这个数据库下

>cls # 清除屏幕上的内容

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Wx4d0gk2-1652786798076)(MongoDB.assets/1652586684191.png)]

创建库为什么看不到呢?

因为:在mongodb中如果数据库中没有任何集合(数据)的时候默认这个库不显示,可以通过db来查看当前所在的库

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4XAblxqo-1652786798076)(MongoDB.assets/1652586856156.png)]

插入数据:

> db.users.insert({name:'li'});
WriteResult({ "nInserted" : 1 })
> 

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BIdkGuOG-1652786798077)(MongoDB.assets/1652590351136.png)]

这个时候就可以看到数据库了

  • 删除数据库
>db.dropDatabase();

集合

  • 查看数据库中所有集合
> show collections; | show tables;

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tm2D4Oxd-1652786798077)(MongoDB.assets/1652591347193.png)]

  • 创建集合
> db.creatCollection('集合名称',[options])

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CXEPAxTD-1652786798078)(MongoDB.assets/1652591429475.png)]

> db.createCollection('products',{max:100,capped:true,size:5000});
{ "ok" : 1 }
> 

options可以是如下参数:

字段 类型 描述
capped 布尔 (可选)如果为true,则创建固定集合。固定集合是指有着固定大小的集合,当达到最大值时,它会自动覆盖最早的文档。当该值为true时,必须指定size参数。
size 数值 (可选)为固定集合指定一个最大值,即字节数。如果capped为true,也需要指定该字段。
max 数值 (可选)指定固定集合中包含文档的最大数量。

注意:当集合不存在时,向集合中插入文格也会自动创建该集合。

  • 删除集合
db.集合名称.drop();

> db.products.drop();
true
> 

文档

官方文档地址: MongoDB CRUD Operations — MongoDB Manual

插入文档

  • 单条文档

  • db.集合名称.insert( { "name":"li" , " age" :18 , "bir":"2004-5-20"});
    
    
  • 多条文档

    db.集合名称.insertMany(
    [ <document 1> , <document 2>, ... ],
    {
        writeConcern: 1,ll写入策略,默认为1,即要求确认写操作,日是不要求。ordered: true l/指定是否按顺序写入,默认true,按顺序写入。
     }
    )
    db.集合名称.insert([
        { "name":"li”, "age" :18 , "bir" : "2004-5-20"}, { "name" : "ling" , "age" :20, "bir" : "2002-5-20"}
    ]);
    
    
    > db.users.insert({name:'li',age:18,bir:'2004-5-20'});
    WriteResult({ "nInserted" : 1 })
    > db.users.insertMany([{name:'li',age:18},{_id:1,name:'ling',age:21}]);
    {
    	"acknowledged" : true,
    	"insertedIds" : [
    		ObjectId("628093fc01acffadf5d96f67"),
    		1
    	]
    }
    > db.users.insert([{name:'li',age:18},{name:'ling',age:21}]);
    BulkWriteResult({
    	"writeErrors" : [ ],
    	"writeConcernErrors" : [ ],
    	"nInserted" : 2,
    	"nUpserted" : 0,
    	"nMatched" : 0,
    	"nModified" : 0,
    	"nRemoved" : 0,
    	"upserted" : [ ]
    })
    > 
    
    

    脚本方式

    for(let i=0;i<100;i++){ 
              
      db.users.insert( { 
               "_id" :i , " name" :"li_"+i, "age" :23});
    }
    
    

    注意:在mongodb中每个文档都会有一个_id作为唯一标识,_id默认会自动生成如果手动指定将使用手动指定的值作为_id 的值。

  • 查询所有

db.集合名称.find();

删除文档

db.集合名称.rexove(
<query>,
  {
     justOne: <boolean>,
     writeConcern: <document>
   }
 )

参数说明:

o query :可选删除的文档的条件。
o justOne:可选如果设为true 或1,则只删除一个文档,如果不设置该参数,或使用默认值false,则删除所有匹配条件的文档。
o writeConcern:可选抛出异常的级别。

更新文档

db.集合名称.update(
<query>,
<update>,
    {
      upsert: <boolean>,
      multi : <boolean>,
      writeConcern : <document>
    }
   );

参数说明:
  • query : update的查询条件,类似sql update查询内where后面的。
  • update : update的对象和一些更新的操作符(如s,$inc…)等,也可以理解为sqlupdate查询内set后面
  • upsert:可选,这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。
  • multi :可选,mongodb默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。
  • writeConcern :可选,抛出异常的级别。
- db.集合名称.update( {
    
       "name" :"zhangsan" } , {name :"li",bir:new date()))
-- 这个更新是将符合条件的全部更新成后面的文档,相当于先删除在更新
- db.集合名称.update( {
    
       "name" : "li" },{$set:{name : " ali")})
-- 保留原来数据更新,但是只更新符合条件的第一条数据
- db.集合名称.update( {name:"li"},{$set: {name:"ling"}},{multi:true})
-- 保留原来数据更新,更新符合条件的所有数据
- db.集合名称.update( {name :"li"},{$set:{name: "ling"}},{multi:true, upsert:true})
  -- 保留原来数据更新,更新符合条件的所有数据没有条件符合时插入数据

文档查询

MongoDB查询文档使用fixd()方法。find(方法以非结构化的方式来显示所有文档。

语法
db.集合名称.find ( query, projection)

  • query:可选,使用查询操作符指定查询条件

  • projection:可选,使用投影操作符指定返回的键。查询时返回文档中所有键值,只需省略该参数即可(默认省略)。

如果你需要以易读的方式来读取数据,可以使用pretty()方法,语法格式如下:

db.集合名称.find ( ) .pretty ()

注意:pretty()方法以格式化的方式来显示所有文档.

对比语法

如果你熟悉常规的sQL 数据,通过下表可以更好的理解MongoDB的条件语句查询:

操作 格式 范例 RDBMS中的类似语句
等于 {:} db.col.find({“by”:“菜鸟教程”}).pretty() where by = ‘菜鸟教程’
小于 {:{$lt:}} db.col.find({“likes”:{$lt:50}}).pretty() where likes < 50
小于或等于 {:{$lte:}} db.col.find({“likes”:{$lte:50}}).pretty() where likes <= 50
大于 {:{$gt:}} db.col.find({“likes”:{$gt:50}}).pretty() where likes > 50
大于或等于 {:{$gte:}} db.col.find({“likes”:{$gte:50}}).pretty() where likes >= 50
不等于 {:{$ne:}} db.col.find({“likes”:{$ne:50}}).pretty() where likes != 50
AND
>db.col.find({key1:value1, key2:value2,....}).pretty()

类似于wHERE语句:WHERE key1=value1 AND key2=value2

OR

MongoDB OR 条件语句使用了关键字 $or,语法格式如下:

>db.col.find(
   {
      $or: [
         {key1: value1}, {key2:value2}
      ]
   }
).pretty()

类似于WHERE语句:霞ERE key1=value1 or key2=value2

AND和OR联合
db.集合名称.find( {
    
       "age": {$gt :50},$or : [{
    
       "name”:“li"},{
    
       "name" :
"MongoDB"}]}).pretty(o):

类似SQL语句为: "where age >50 AND(name =“li’OR name = ’ MongoDB’)

数组中查询
-- 测试数据
> db.集合名称.insert({ "_id" : 11, "age" : 22, "likes" : [ "ling", "li" ], "name" : "li_11" })
-- 执行数组查询
> db.users.find({likes:"ling"})
{ "_id" : 11, "age" : 22, "likes" : [ "ling", "li" ], "name" : "li_11" }

模糊查询

类似于SQL中为 where name like ‘%name%’

> db.users.find({name:/li/});
{ "_id" : 0, "name" : "li_0", "age" : 18 }
{ "_id" : 1, "name" : "li_1", "age" : 18 }
{ "_id" : 2, "name" : "li_2", "age" : 18 }
{ "_id" : 3, "name" : "li_3", "age" : 18 }
{ "_id" : 4, "name" : "li_4", "age" : 18 }
{ "_id" : 5, "name" : "li_5", "age" : 18 }
{ "_id" : 6, "name" : "li_6", "age" : 18 }
{ "_id" : 7, "name" : "li_7", "age" : 18 }
{ "_id" : 8, "name" : "li_8", "age" : 18 }
{ "_id" : 9, "name" : "li_9", "age" : 18 }
{ "_id" : 11, "age" : 22, "likes" : [ "ling", "li" ], "name" : "li_11" }
> db.users.find({likes:/ling/});
{ "_id" : 11, "age" : 22, "likes" : [ "ling", "li" ], "name" : "li_11" }
> 
-- $size 按照数据长度查询
> db.users.find({likes:{$size:2}});

注意:在mongoDB中使用正则表达式可以是实现近似模糊查询功能

排序
 db.集合名称.find ( ).sort({name : 1,age:1}).-1升序-1降序

类似 SQL语甸为: 'order by name , age ’

分页
db.集合名称.find() . sort({条件}).skip(start) . 

相关文章