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

本文涉及的产品
云原生数据库 PolarDB MySQL 版,Serverless 5000PCU 100GB
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
云数据库 MongoDB,通用型 2核4GB
简介: 小白必须懂的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 将会是利器。

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

  • 面向集合存储,易存储对象类型的数据。
  • 模式自由。
  • 支持动态查询。
  • 支持完全索引,包含内部对象。
  • 支持查询。
  • 支持复制和故障恢复。
  • 使用高效的二进制数据存储,包括大型对象(如视频等)。
  • 自动处理碎片,以支持云计算层次的扩展性
  • 支持 PythonPHPRubyJavaCC#JavascriptPerlC++ 语言的驱动程序,社区中也提供了对 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 数据的存储:MongoBSON 数据格式非常适合文档化格式的存储及查询。

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


相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。   相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
目录
相关文章
|
5月前
|
运维 NoSQL MongoDB
[慕课笔记]mongodb入门篇
[慕课笔记]mongodb入门篇
41 1
|
5月前
|
NoSQL 数据可视化 MongoDB
mongoDB从入门到实战最全小白教程
mongoDB从入门到实战最全小白教程
285 0
|
JSON NoSQL 关系型数据库
小白必须懂的MongoDB的十大总结(下)
小白必须懂的MongoDB的十大总结(下)
145 0
小白必须懂的MongoDB的十大总结(下)
|
存储 SQL JSON
走进 MongoDB|学习笔记
快速学习走进 MongoDB
195 0
走进 MongoDB|学习笔记
|
存储 SQL NoSQL
MongoDB必备知识点全面总结(四)
MongoDB必备知识点全面总结
190 0
MongoDB必备知识点全面总结(四)
|
存储 JSON NoSQL
MongoDB必备知识点全面总结(三)
MongoDB必备知识点全面总结
250 0
MongoDB必备知识点全面总结(三)
|
存储 JSON NoSQL
MongoDB必备知识点全面总结(一)
MongoDB必备知识点全面总结
545 0
MongoDB必备知识点全面总结(一)
|
存储 NoSQL JavaScript
MongoDB必备知识点全面总结(二)
MongoDB必备知识点全面总结
297 0
MongoDB必备知识点全面总结(二)
|
设计模式 机器学习/深度学习 JSON
『MongoDB』MongoDB模型设计的成神之路
📣读完这篇文章里你能收获到 - 为什么很多人认为MongoDB是无模式? - 文档模型跟传统的关系模型有什么区别? - 关于MongoDB的模型设计模式,你知道几个? - MongoDB如何进行表关联? - 文档模型的设计规范及设计原则 - 文档建模模型设计三部曲 - 1-1关系建模,1-N关系建模,N-N关系建模的建议 - 针对不同的场景提供丰富的设计案例分享
373 0
『MongoDB』MongoDB模型设计的成神之路
|
JSON NoSQL 安全
走进 MongoDB
了解MongoDB相关概念和基本操作。
走进 MongoDB