小白必须懂的MongoDB的十大总结(上)

简介: 小白必须懂的MongoDB的十大总结(上)

小白必须懂的MongoDB的总结

一、MongoDB的认识

1、什么是MongoDB?

MongoDB 是一个介于关系数据库和非关系数据库之间的开源产品,是最接近于关系型数据库的 NoSQL 数据库。它在轻量级JSON 交换基础之上进行了扩展,即称为 BSON 的方式来描述其无结构化的数据类型。尽管如此它同样可以存储较为复杂的数据类型。它和上一篇文章讲到的Redis有异曲同工之妙。虽然两者均为 NoSQL ,但是 MongoDB 相对于 Redis 而言,MongoDB 更像是传统的数据库。早些年我们是先有了 Relation Database (关系型数据库),然后出现了很多很复杂的query ,里面用到了很多嵌套,很多 join 操作。所以在设计数据库的时候,我们也考虑到了如何应用他们的关系,使得写 query 可以使 database 效率达到最高。后来人们发现,不是每个系统,都需要如此复杂的关系型数据库。有些简单的网站,比如博客,比如社交网站,完全可以斩断数据库之间的一切关系。这样做带来的好处是,设计数据库变得更加简单,写 query 也变得更加简单。然后,query 消耗的时间可能也会变少。因为 query 简单了,少了许多消耗资源的 join 操作,速度自然会上去。正如所说的, query 简单了,很有以前 MySQL 可以找到的东西,现在关系没了,通过 Mongo 找不到了。我们只能将几组数据都抓到本地,然后在本地做 join ,所以在这点上可能会消耗很多资源。这里我们可以发现。如何选择数据库,完全取决于你所需要处理的数据的模型,即 Data Model 。如果它们之间,关系错综复杂,千丝万缕,这个时候 MySQL 一定是首选。如果他们的关系并不是那么密切,那么, NoSQL 将会是利器。

MongoDB 和 Redis 一样均为 key-value 存储系统,它具有以下特点:

  • 面向集合存储,易存储对象类型的数据。
  • 模式自由。
  • 支持动态查询。
  • 支持完全索引,包含内部对象。
  • 支持查询。
  • 支持复制和故障恢复。
  • 使用高效的二进制数据存储,包括大型对象(如视频等)。
  • 自动处理碎片,以支持云计算层次的扩展性
  • 支持 Python , PHP , Ruby , Java , C , C# , Javascript ,Perl 及 C++ 语言的驱动程序,社区中也提供了对 Erlang 及 .NET 等平台的驱动程序。
  • 文件存储格式为 BSON (一种 JSON 的扩展)。
  • 可通过网络访问。

2、MongoDB与MySQL性能比较

像 MySQL 一样, MongoDB 提供了丰富的远远超出了简单的键值存储中提供的功能和功能。 MongoDB 具有查询语言,功能强大的辅助索引(包括文本搜索和地理空间),数据分析功能强大的聚合框架等。相比使用关系数据库而言,使用MongoDB ,您还可以使用如下表所示的这些功能,跨越更多样化的数据类型和数据规模。

MySQL MongoDB
丰富的数据模型 否 是
动态 Schema 否 是
数据类型 是 是
数据本地化 否 是
字段更新 是 是
易于编程 否 是
复杂事务 是 否
审计 是 是
自动分片 否 是

MySQL 中的许多概念在 MongoDB 中具有相近的类比。本表概述了每个系统中的一些常见概念。

MySQL MongoDB
表 集合
行 文档
列 字段
joins 嵌入文档或者链接

3、应用范围和限制

MongoDB 的主要目标是在 key-value (键/值)存储方式(提供了高性能和高度伸缩性)以及传统的 RDBMS 系统(丰富的功能)架起一座桥梁,集两者的优势于一身。 MongoDB 适用范围如下:

  • 网站数据:Mongo 非常适合实时的插入,更新与查询,并具备网站实时数据存储所需的复制及高度伸缩性。
  • 缓存:由于性能很高, Mongo 也适合作为信息基础设施的缓存层。在系统重启之后,由 Mongo 搭建的持久化缓存层可以避免下层的数据源过载。
  • 大尺寸,低价值的数据:使用传统的关系型数据库存储一些数据时可能会比较昂贵,在此之前,很多时候程序员往往会选择传统的文件进行存储。
  • 高伸缩性的场景:Mongo 非常适合由数十或数百台服务器组成的数据库。 Mongo 的路线图中已经包含对 MapReduce 引擎的内置支持。
  • 用于对象及 JSON 数据的存储:Mongo 的 BSON 数据格式非常适合文档化格式的存储及查询。

MongoDB 当然也会有以下场景的限制:

  • 高度事物性的系统:例如银行或会计系统。传统的关系型数据库目前还是更适用于需要大量原子性复杂事务的应用程序。
  • 传统的商业智能应用:针对特定问题的 BI 数据库会对产生高度优化的查询方式。对于此类应用,数据仓库可能是更合适的选择。
  • 需要 SQL 的问题。

二、MongoDB的安装

环境准备

安装步骤

1、创建一个 mongodb-org-3.6.repo 文件
vi /etc/yum.repos.d/mongodb-org-3.6.repo

在文件中加入如下内容:

[mongodb-org-3.6]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/amazon/2013.03/mongodb-org/3.6/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-3.6.asc

退出编辑模式,直接输入如下命令安装即可:

sudo yum install -y mongodb-org

img_5e4fae036fceb5c6fe24a50e70f887f4.png

若要安装特定版本的 MongoDB ,请分别指定每个组件包并将版本号附加到包名称,如下所示:

sudo yum install -y mongodb-org-3.6.3 mongodb-org-server-3.6.3 mongodb-org-shell-3.6.3 mongodb-org-mongos-3.6.3 mongodb-org-tools-3.6.3

你可以指定任何可用的 MongoDB 版本。然而, yum 会在新版本可用时升级软件包。为防止意外升级,请钉住包装。要固定软件包,请将以下 exclude 指令添加到 /etc/yum.conf 文件中:

exclude=mongodb-org,mongodb-org-server,mongodb-org-shell,mongodb-org-mongos,mongodb-org-tools

我们直接运行如下命令:

mongod -repair

看到如下字样,说明我们安装成功!


img_465876e5c7bd7329eeb1d7341e57b171.png

我们创建一个 db ,并查看下 mongo 的安装位置:

mkdir db
whereis mongod


img_51101499ae10e0a3b9183fa66d72139e.png

安装完成后启动 mongodb ,并查看下 mongob 启动状态:

systemctl start mongod.service
systemctl status mongod.service

如果出现如下字样,说明启动成功!

img_010359f19ebba8d51e3b2fd298647aaf.png

成功启动 MongoDB 后,新建一个命令行输入 mongo 进行登录操作,即可进行数据库的一些操作了。

mongo

img_8c42a304fb124b3a8e2aa7df0b5de532.png

三、MongoDB数据类型及常用命令讲解

MongoDB 的数据类型大致有下列几种:

数据类型 描述
String 字符串。存储数据常用的数据类型。在 MongoDB 中,UTF-8 编码的字符串才是合法的。
Integer 整型数值。用于存储数值。根据你所采用的服务器,可分为 32 位或 64 位。
Boolean 布尔值。用于存储布尔值(真/假)。
Double 双精度浮点值。用于存储浮点值。
Min/Max keys 将一个值与 BSON (二进制的 JSON)元素的最低值和最高值相对比。
Arrays 用于将数组或列表或多个值存储为一个键。
Timestamp 时间戳。记录文档修改或添加的具体时间。
Object 用于内嵌文档。
Null 用于创建空值。
Symbol 符号。该数据类型基本上等同于字符串类型,但不同的是,它一般用于采用特殊符号类型的语言。
Date 日期时间。用 UNIX 时间格式来存储当前日期或时间。你可以指定自己的日期时间:创建 Date 对象,传入年月日信息。
Object ID 对象 ID。用于创建文档的 ID。
Binary Data 二进制数据。用于存储二进制数据。
Code 代码类型。用于在文档中存储 JavaScript 代码。
Regular expression 正则表达式类型。用于存储正则表达式。

下面我们将介绍一些 MongoDB 的常用命令!

1、创建数据库

use 数据库名称 :创建一个新的数据库。注意:如果该数据库不存在,则创建,如果该数据库存在,则是切换

如果创建了数据库,没有任何的操作,则会自动删除该数据库

example:

> use stu
switched to db stu
2、查看数据库

show dbs :查看当前有多少个数据库

example:

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
3、创建集合

db.集合名.insert({}) :向集合里面,添加文档。{} 里面是 json 的文档。注意: mongodb 里面的集合是隐式创建,就是无需创建,直接使用。 db 表示显示当前所在的数据库。

example:

> db.php.insert({"name":"xiaoming","age":20,"email":"xiaoming@gmail.com"})
WriteResult({ "nInserted" : 1 })
> db.php.insert({"name":"xiaohong","age":18,"email":"xiaohong@gmail.com"})
WriteResult({ "nInserted" : 1 })
4、查看集合

show tables :查看当前数据库中的集合

example:

> show tables
php
5、查询集合里面的文档

db.集合名.find() :查询当前数据库中该集合下的所有文档

example:

> db.php.find()
{ "_id" : ObjectId("5b9318ac487b851e62879578"), "name" : "xiaoming", "age" : 20, "email" : "xiaoming@gmail.com" }
{ "_id" : ObjectId("5b9319a2487b851e62879579"), "name" : "xiaohong", "age" : 18, "email" : "xiaohong@gmail.com" }

db.集合名.find :查询当前数据库中该集合下的第一个文档

example:

> db.php.find
function (query, fields, limit, skip, batchSize, options) {
    var cursor = new DBQuery(this._mongo,
                             this._db,
                             this,
                             this._fullName,
                             this._massageObject(query),
                             fields,
                             limit,
                             skip,
                             batchSize,
                             options || this.getQueryOptions());
    {
        const session = this.getDB().getSession();
        const readPreference = session._serverSession.client.getReadPreference(session);
        if (readPreference !== null) {
            cursor.readPref(readPreference.mode, readPreference.tags);
        }
        const readConcern = session._serverSession.client.getReadConcern(session);
        if (readConcern !== null) {
            cursor.readConcern(readConcern.level);
        }
    }
    return cursor;
}
6、删除集合

db.集合名.drop() :删除当前数据库中的集合

example:

> db.php.drop()
true
7、删除数据库

db.dropDatabase() :删除当前的数据库

> db.dropDatabase()
{ "dropped" : "stu", "ok" : 1 }
8、帮助命令

help :全局帮助命令

> help
    db.help()                    help on db methods
    db.mycoll.help()             help on collection methods
    sh.help()                    sharding helpers
    rs.help()                    replica set helpers
    help admin                   administrative help
    help connect                 connecting to a db help
    help keys                    key shortcuts
    help misc                    misc things to know
    help mr                      mapreduce
    show dbs                     show database names
    show collections             show collections in current database
    show users                   show users in current database
    show profile                 show most recent system.profile entries with time >= 1ms
    show logs                    show the accessible logger names
    show log [name]              prints out the last segment of log in memory, 'global' is default
    use                 set current database
    db.foo.find()                list objects in collection foo
    db.foo.find( { a : 1 } )     list objects in foo where a == 1
    it                           result of the last line evaluated; use to further iterate
    DBQuery.shellBatchSize = x   set default number of items to display on shell
    exit                         quit the mongo shell

db.help() :数据库相关的帮助命令

example:

> db.help()
DB methods:
    db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [just calls db.runCommand(...)]
    db.aggregate([pipeline], {options}) - performs a collectionless aggregation on this database; returns a cursor
    db.auth(username, password)
    db.cloneDatabase(fromhost)
    db.commandHelp(name) returns the help for the command
    db.copyDatabase(fromdb, todb, fromhost)
    db.createCollection(name, {size: ..., capped: ..., max: ...})
    db.createView(name, viewOn, [{$operator: {...}}, ...], {viewOptions})
    db.createUser(userDocument)
    db.currentOp() displays currently executing operations in the db
    db.dropDatabase()
    db.eval() - deprecated
    db.fsyncLock() flush data to disk and lock server for backups
    db.fsyncUnlock() unlocks server following a db.fsyncLock()
    db.getCollection(cname) same as db['cname'] or db.cname
    db.getCollectionInfos([filter]) - returns a list that contains the names and options of the db's collections
    db.getCollectionNames()
    db.getLastError() - just returns the err msg string
    db.getLastErrorObj() - return full status object
    db.getLogComponents()
    db.getMongo() get the server connection object
    db.getMongo().setSlaveOk() allow queries on a replication slave server
    db.getName()
    db.getPrevError()
    db.getProfilingLevel() - deprecated
    db.getProfilingStatus() - returns if profiling is on and slow threshold
    db.getReplicationInfo()
    db.getSiblingDB(name) get the db at the same server as this one
    db.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set
    db.hostInfo() get details about the server's host
    db.isMaster() check replica primary status
    db.killOp(opid) kills the current operation in the db
    db.listCommands() lists all the db commands
    db.loadServerScripts() loads all the scripts in db.system.js
    db.logout()
    db.printCollectionStats()
    db.printReplicationInfo()
    db.printShardingStatus()
    db.printSlaveReplicationInfo()
    db.dropUser(username)
    db.repairDatabase()
    db.resetError()
    db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into {cmdObj: 1}
    db.serverStatus()
    db.setLogLevel(level,)
    db.setProfilingLevel(level,slowms) 0=off 1=slow 2=all
    db.setWriteConcern() - sets the write concern for writes to the db
    db.unsetWriteConcern() - unsets the write concern for writes to the db
    db.setVerboseShell(flag) display extra information in shell output
    db.shutdownServer()
    db.stats()
    db.version() current version of the server

db.集合名.help() :集合相关的帮助命令

example:

> db.php.help()
DBCollection help
    db.php.find().help() - show DBCursor help
    db.php.bulkWrite( operations,  ) - bulk execute write operations, optional parameters are: w, wtimeout, j
    db.php.count( query = {},  ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS
    db.php.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.
    db.php.convertToCapped(maxBytes) - calls {convertToCapped:'php', size:maxBytes}} command
    db.php.createIndex(keypattern[,options])
    db.php.createIndexes([keypatterns], )
    db.php.dataSize()
    db.php.deleteOne( filter,  ) - delete first matching document, optional parameters are: w, wtimeout, j
    db.php.deleteMany( filter,  ) - delete all matching documents, optional parameters are: w, wtimeout, j
    db.php.distinct( key, query,  ) - e.g. db.php.distinct( 'x' ), optional parameters are: maxTimeMS
    db.php.drop() drop the collection
    db.php.dropIndex(index) - e.g. db.php.dropIndex( "indexName" ) or db.php.dropIndex( { "indexKey" : 1 } )
    db.php.dropIndexes()
    db.php.ensureIndex(keypattern[,options]) - DEPRECATED, use createIndex() instead
    db.php.explain().help() - show explain help
    db.php.reIndex()
    db.php.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
                                                  e.g. db.php.find( {x:77} , {name:1, x:1} )
    db.php.find(...).count()
    db.php.find(...).limit(n)
    db.php.find(...).skip(n)
    db.php.find(...).sort(...)
    db.php.findOne([query], [fields], [options], [readConcern])
    db.php.findOneAndDelete( filter,  ) - delete first matching document, optional parameters are: projection, sort, maxTimeMS
    db.php.findOneAndReplace( filter, replacement,  ) - replace first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument
    db.php.findOneAndUpdate( filter, update,  ) - update first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument
    db.php.getDB() get DB object associated with collection
    db.php.getPlanCache() get query plan cache associated with collection
    db.php.getIndexes()
    db.php.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
    db.php.insert(obj)
    db.php.insertOne( obj,  ) - insert a document, optional parameters are: w, wtimeout, j
    db.php.insertMany( [objects],  ) - insert multiple documents, optional parameters are: w, wtimeout, j
    db.php.mapReduce( mapFunction , reduceFunction ,  )
    db.php.aggregate( [pipeline],  ) - performs an aggregation on a collection; returns a cursor
    db.php.remove(query)
    db.php.replaceOne( filter, replacement,  ) - replace the first matching document, optional parameters are: upsert, w, wtimeout, j
    db.php.renameCollection( newName ,  ) renames the collection.
    db.php.runCommand( name ,  ) runs a db command with the given name where the first param is the collection name
    db.php.save(obj)
    db.php.stats({scale: N, indexDetails: true/false, indexDetailsKey: , indexDetailsName: })
    db.php.storageSize() - includes free space allocated to this collection
    db.php.totalIndexSize() - size in bytes of all the indexes
    db.php.totalSize() - storage allocated for all data and indexes
    db.php.update( query, object[, upsert_bool, multi_bool] ) - instead of two flags, you can pass an object with fields: upsert, multi
    db.php.updateOne( filter, update,  ) - update the first matching document, optional parameters are: upsert, w, wtimeout, j
    db.php.updateMany( filter, update,  ) - update all matching documents, optional parameters are: upsert, w, wtimeout, j
    db.php.validate(  ) - SLOW
    db.php.getShardVersion() - only for use with sharding
    db.php.getShardDistribution() - prints statistics about data distribution in the cluster
    db.php.getSplitKeysForChunks(  ) - calculates split points over all chunks and returns splitter function
    db.php.getWriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set
    db.php.setWriteConcern(  ) - sets the write concern for writes to the collection
    db.php.unsetWriteConcern(  ) - unsets the write concern for writes to the collection
    db.php.latencyStats() - display operation latency histograms for this collection


目录
相关文章
|
存储 缓存 监控
一文读懂分布式架构知识体系(内含超全核心知识大图)
7月9日 19:00-21:30 阿里云开发者社区首场“Offer 5000”直播开启!15位团队技术大牛在线招人,更有《阿里云技术面试红宝书》助你拿下Offer!马上投递简历:https://developer.aliyun.com/special/offerday01
21060 0
|
存储 NoSQL 前端开发
【赵渝强老师】MongoDB的分布式存储架构
MongoDB分片通过将数据分布到多台服务器,实现海量数据的高效存储与读写。其架构包含路由、配置服务器和分片服务器,支持水平扩展,结合复制集保障高可用性,适用于大规模生产环境。
908 1
|
12月前
|
人工智能 监控 安全
别等上线才后悔!AI应用测试的5个维度与4类实战避坑指南
某心理App上线AI打卡功能后因“张冠李戴”遭投诉,暴露大模型测试新挑战。传统测试难应对AI的不确定性,需构建覆盖准确性、鲁棒性、安全性、性能与合规性的五维框架,从“流程检验”转向“智能体守护”,确保AI输出精准、安全、有温度。
|
11月前
|
存储 机器学习/深度学习 算法
交易所平台系统开发:关键功能与技术剖析
本文深入解析交易所平台系统架构与核心功能,涵盖分层设计、微服务架构及容器化部署方案,重点探讨交易撮合引擎与风控系统的技术实现,为开发者提供高性能、高可用的系统开发参考框架。
|
12月前
|
数据采集 存储 监控
数据资产是什么?企业该如何做好数据资产管理?
企业常陷数据内耗:报表打架、口径不一、决策靠经验。真正的数据资产需权属清晰、质量可靠、业务可用。数据资产管理不是IT项目,而是从业务出发的系统性变革,通过治理、盘货、运营、应用四层框架,让数据找得到、信得过、用得好。中小型企业也应轻量起步,聚焦核心指标,推动数据驱动文化,实现提效避坑。
|
Linux 数据库 iOS开发
CrossOver 25.1.0 for macOS & Linux - 领先的 Wine 解决方案
CrossOver 25.1.0 for macOS & Linux - 领先的 Wine 解决方案
1011 0
|
存储 弹性计算 人工智能
租用阿里云服务器关心的价格问题:CPU内存+带宽+存储收费标准,2025最新整理
本文整理2025年最新阿里云服务器租用费用,涵盖轻量应用服务器、ECS云服务器及GPU服务器等多种类型。爆款配置如200M带宽轻量服务器低至38元/年,ECS经济型e实例2核2G仅需99元/年,企业专享2核4G服务器199元/年。高配如4核16G、8核32G服务器也有多档优惠,支持按年、按月购买,适用于个人开发者、中小企业及高性能计算场景。
|
Java Linux Shell
centos7内网离线安装face_recognition、python、pip、CMake、dlib,离线升级gcc/切换gcc,文末有face_recognition的docker版本
公司项目需要人脸识别,本来app自带人脸识别,结果api支持的设备试了一圈就一个同事的华为Mate40Pro可以,所以使用无望。接着找了一下免费的java离线人脸识别sdk,发现虹软的确实简单好用,一会就在linux上弄好并测试通过了,然而在准备集成进去开写代码时,不小心看到了一眼首次激活需联网,后续方可离线使用,好吧,我们内网机器首次都不可能的,接着看了下离线激活方法,首先需要企业认证,这一步我们肯定没法做的,毕竟不是之前的小公司了,营业执照啥的随便给我肯定不行,直接放弃了。后来在同事推荐下看了下face_recognition这个项目,之前基本没用过python,于是有了漫长的踩坑之旅。
1968 1
|
存储 SQL 运维
当「内容科技企业」遇上多模数据库:新榜采用Lindorm打造全域数据“超级底盘”
新榜业务以数据服务提升内容产业信息流通效率,其数据处理需求聚焦于跨平台实时数据融合处理、实时分析检索、批量更新效率三大维度。Lindorm通过多模超融合架构,提供检索分析一体化、多引擎数据共享,分布式弹性扩展等能力,成为支撑新榜内容服务的核心引擎,助力客户在内容生态竞争中持续领跑。
|
存储 自然语言处理 关系型数据库
基于阿里云通义千问开发智能客服与问答系统
在企业的数字化转型过程中,智能客服系统已成为提高客户满意度和降低运营成本的重要手段。阿里云的通义千问作为一款强大的大语言模型,具有自然语言理解、对话生成、知识检索等能力,非常适合用来开发智能客服与问答系统。 通过本博客,我们将演示如何基于阿里云的通义千问模型,结合阿里云相关产品如函数计算(FC)、API网关、RDS等,搭建一个功能齐全的智能客服系统。
2497 5