MongoDB简介、数据类型及帮助命令

本文涉及的产品
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
简介: MongoDB 是一个可扩展、高性能的 NoSQL 数据库,由 C++ 语言编写,旨在为 web 应用提供高性能可扩展的数据存储解决方案。它的特点是高性能、易部署、易使用,存储数据非常方便,主要特性有:


一、MongoDB 介绍



1. MongoDB 的特点

MongoDB 是一个可扩展、高性能的 NoSQL 数据库,由 C++ 语言编写,旨在为 web 应用提供高性能可扩展的数据存储解决方案。

它的特点是高性能、易部署、易使用,存储数据非常方便,主要特性有:

  • 模式自由,支持动态查询、完全索引,可轻易查询文档中内嵌的对象及数组。
  • 面向集合存储,易存储对象类型的数据 , 包括文档内嵌对象及数组。
  • 高效的数据存储 , 支持二进制数据及大型对象 ( 如照片和视频 )。
  • 支持复制和故障恢复;提供了 主-从、主-主模式的数据复制及服务器之间的数据复制。
  • 自动分片以支持云级别的伸缩性,支持水平的数据库集群,可动态添加额外的服务器。


2. MongoDB的优点与适用场景

MongoDB的优点

  • 高性能,速度非常快(如果你的内存足够的话)。
  • 没有固定的表结构,不用为了修改表结构而进行数据迁移。
  • 查询语言简单,容易上手。
  • 使用Sharding实现水平扩展。
  • 部署方便。

MongoDB的适用场景

  • 适合作为信息基础设施的持久化缓存层 。
  • 适合实时的插入,更新与查询,并具备应用程序实时数据存储所需的复制及高度伸缩性。
  • Mongo 的 BSON 数据格式非常适合文档化格式的存储及查询。
  • 适合由数十或数百台服务器组成的数据库。因为Mongo 已经包含了对 MapReduce 引擎的内置支持。


二、SQL 与 NoSQL对比



- SQL数据库 NoSQL数据库
类型 所有类型都支持SQL标准 存在多种类型,比如文档存储、键值存储、列数据库等
示例 MySQL、SQL Server、Oracle MongoDB、HBase、Cassandra
数据存储模型 数据被存储在表的行和列中,其中每一列都有一个特定类型。
表通常都是按照标准化原则创建的。
使用联接来从多个表中检索数据。
数据模型取决于数据库类型。
比如数据被存储为键值对以用于键值存储。在基于文档的数据库中,数据会被存储为文档。
NoSQL的数据模型是灵活的,与SQL数据库死板的表模型相反。
模式 固定的结构和模式,因此对模式的任何变更都涉及修改数据库 动态模式,通过扩展或修改当前模式就能适应新的数据类型或结构。
可以动态添加新的字段
可扩展性 使用了纵向扩展方式。这意味着随着负荷的增加,需要购买更大、更贵的服务器来容纳数据。 使用了横向扩展方式。这意味着可以将数据负荷分散到多台廉价服务器上。
支持事务 支持ACID和事务 支持分区和可用性,会损害事务。
事务存在于某个级别,比如数据库级别或文档级别。
一致性 强一致性 取决于产品。有些产品选择提供强一致性,而有些提供最终一致性。
查询功能 可通过易用的GUI界面来使用 查询可能需要编程专业技术和知识。与UI不同,其重心在于功能和编程接口


MongoDB 与 Mysql 概念对应关系

mongodb mysql
数据库(datebase) 数据库(datebase)
集合(collection) 表(table)
文档(document) 记录(row)
字段 列 / 字段
索引 索引
嵌入和引用 表内联结


三、MongoDB 支持的数据类型



1. null

null用于表示空值或不存在的字段

{ "x" : null }

2. 布尔

布尔类型有两个值 true 和 false

{ "x": true }

3. 32位整数

在 Mongo Shell 中不支持这个类型。JavaScript仅支持64位浮点数,所以32位整数会被自动转换为64位浮点数。

4. 64位整数

在 Mongo Shell 中也不支持这个类型。Mongo Shell 会使用一个特殊的内嵌文档来显示64位整数。

5. 64位浮点数

Mongo Shell 中的数字都是这种类型。

{  "pi" : 3.14 }
JavaScript 中只有一种 “数字” 类型。因为 MongoDB 中有3种数字类型(32位整数、64位整数和64位浮点数), shell 必须绕过 JavaScript 的限制。默认情况下,shell 中的数字都被 MongoDB 当做是双精度数。这意味着如果你从数据库中获得的是一个32位整数,修改文档后,将文档存回数据库的时候,这个整数也被转换成了浮点数,即便保持这个整数原封不动也会这样的。所以明智的做法是尽量不要在 shell 下覆盖整个文档。

数字只能表示为双精度数(64位浮点数)的另外一个问题是,有些64位的整数并不能精确地表示为64位浮点数。所以,如果存入了一个64位整数,在shell中查看,它会显示为一个内嵌文档。但是在数据库中实际存储的值是准确的。

32位的整数都能用64位的浮点数精确表示,所以显示起来没什么特别的。

6. 字符串

UTF-8字符串都可表示为字符串类型

{ "x" : "abcde" }

7. 对象id

对象id使用12字节的存储空间,每个字节两位十六进制数字,是一个24位的字符串。

{ "_id" : ObjectId() }

8. 日期

日期类型存储的是亳秒级的时间戳,不存储时区。

{ "d" : new Date() }

9. 正则表达式

文档中可以包含正则表达式,采用JavaScript的正则表达式语法。

{ "x" : /^abc/i }

10. 代码

文档中可以包含JavaScript代码

{ "x" : function(){/********/} }

11. 数组

值的集合或者列表可以表示成数组

{ "d" : [1,2,3,4,5] }

12. 内嵌文档

文档中可以包含其他文档,也可以作为值嵌入到父文档中。

{ "x" : { "y" : "z" } }

13. undefined

文档中也可以使用 undefined((未定义)类型(JavaScript中 null 和 undefined 是不同的类型)。

{ "a" : undefined }

14. 二进制数据

二进制数据可以由任意字节的串组成。可用于存储图片等二进制文件。不过在 Mongo Shell 中无法使用。


四、Mongo Shell 帮助命令



1. 系统级帮助: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 <db_name>                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

2. 查看数据库上可用的操作:db.help()

> 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) - deprecated
        db.commandHelp(name) returns the help for the command
        db.copyDatabase(fromdb, todb, fromhost) - deprecated
        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,<component>)
        db.setProfilingLevel(level,slowms) 0=off 1=slow 2=all
        db.setWriteConcern(<write concern doc>) - sets the write concern for writes to the db
        db.unsetWriteConcern(<write concern doc>) - 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

3. 查看集合上可用的操作:db.集合名.help()

> db.user.help()
DBCollection help
        db.user.find().help() - show DBCursor help
        db.user.bulkWrite( operations, <optional params> ) - bulk execute write operations, optional parameters are: w, wtimeout, j
        # 集合中的记录数
        db.user.count( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS
        db.user.countDocuments( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS
        db.user.estimatedDocumentCount( <optional params> ) - estimate the document count using collection metadata, optional parameters are: maxTimeMS
        db.user.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.
        db.user.convertToCapped(maxBytes) - calls {convertToCapped:'user', size:maxBytes}} command
        db.user.createIndex(keypattern[,options])
        db.user.createIndexes([keypatterns], <options>)
        # 集合大小
        db.user.dataSize()
        db.user.deleteOne( filter, <optional params> ) - delete first matching document, optional parameters are: w, wtimeout, j
        db.user.deleteMany( filter, <optional params> ) - delete all matching documents, optional parameters are: w, wtimeout, j
        db.user.distinct( key, query, <optional params> ) - e.g. db.user.distinct( 'x' ), optional parameters are: maxTimeMS
        # 删除集合
        db.user.drop() drop the collection
        db.user.dropIndex(index) - e.g. db.user.dropIndex( "indexName" ) or db.user.dropIndex( { "indexKey" : 1 } )
        # 删除集合内的所有索引
        db.user.dropIndexes()
        db.user.ensureIndex(keypattern[,options]) - DEPRECATED, use createIndex() instead
        db.user.explain().help() - show explain help
        db.user.reIndex()
        db.user.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
                                                      e.g. db.user.find( {x:77} , {name:1, x:1}
相关文章
|
6月前
|
NoSQL MongoDB 微服务
微服务——MongoDB常用命令——文档的分页查询
本文介绍了文档分页查询的相关内容,包括统计查询、分页列表查询和排序查询。统计查询使用 `count()` 方法获取记录总数或按条件统计;分页查询通过 `limit()` 和 `skip()` 方法实现,控制返回和跳过的数据量;排序查询利用 `sort()` 方法,按指定字段升序(1)或降序(-1)排列。同时提示,`skip()`、`limit()` 和 `sort()` 的执行顺序与编写顺序无关,优先级为 `sort()` &gt; `skip()` &gt; `limit()`。
249 1
|
6月前
|
JSON NoSQL MongoDB
微服务——MongoDB常用命令——文档基本CRUD
本文介绍了MongoDB中文档的基本操作,包括插入、查询、更新和删除。单个文档插入使用`insert()`或`save()`方法,批量插入用`insertMany()`。查询所有文档用`find()`,条件查询可在`find()`中添加参数,投影查询控制返回字段。更新文档通过`update()`实现,支持覆盖修改、局部修改(使用`$set`)和批量修改。列值增长可用`$inc`实现。删除文档用`remove()`,需谨慎操作以免误删数据。此外,文档键值对有序,区分大小写,不能有重复键。
129 1
|
6月前
|
存储 NoSQL MongoDB
微服务——MongoDB常用命令——MongoDB索引知识概述
本文介绍MongoDB索引相关知识,包括其在查询中的重要作用。索引可避免全集合扫描,显著提升查询效率,尤其在处理海量数据时。通过B树数据结构存储字段值并排序,支持相等匹配、范围查询及排序操作。文中还提供了官方文档链接以供深入学习。
96 0
|
2月前
|
JSON NoSQL Shell
MongoDB简介
MongoDB 是一款开源、高性能、无模式的文档型数据库,属于 NoSQL 产品,支持灵活的 BSON 数据格式,结构类似 JSON,适合存储复杂数据。它以文档为最小存储单位,具备高性能、高可用、高扩展性,支持丰富查询及多种数据类型,适用于大规模数据场景。
330 0
|
6月前
|
存储 NoSQL MongoDB
微服务——MongoDB常用命令——MongoDB索引的类型
本节介绍了MongoDB中索引的几种类型及其特点。包括单字段索引,支持升序/降序排序,索引顺序对操作无影响;复合索引,字段顺序重要,可实现多级排序;地理空间索引,支持平面与球面几何查询;文本索引,用于字符串搜索并存储词根;哈希索引,基于字段值散列,适合等值匹配但不支持范围查询。
176 1
微服务——MongoDB常用命令——MongoDB索引的类型
|
6月前
|
存储 JSON NoSQL
MongoDB常用命令
本文介绍了将文章评论数据存储到MongoDB中的操作方法,包括数据库和集合的基本操作。主要内容涵盖:选择与创建数据库(如`articledb`)、数据库删除、集合的显式与隐式创建及删除、文档的CRUD操作(插入、查询、更新、删除)。此外,还详细说明了分页查询、排序查询以及统计查询的方法,例如使用`limit()`、`skip()`实现分页,`sort()`进行排序,`count()`统计记录数。通过实例展示了如何高效管理MongoDB中的数据。
|
6月前
|
NoSQL 关系型数据库 MongoDB
微服务——MongoDB常用命令——集合操作
本节主要介绍MongoDB中的集合操作,包括显式与隐式创建集合的方法。显式创建使用`db.createCollection(name)`,需遵循命名规范(如不能以&quot;system.&quot;开头或包含`\0`字符)。隐式创建则通过直接向不存在的集合插入文档实现,更为常用。此外,还介绍了集合删除方法`db.collection.drop()`及其返回值规则,帮助用户管理数据库中的集合资源。
233 0
|
6月前
|
存储 NoSQL MongoDB
微服务——MongoDB常用命令1——数据库操作
本节介绍了 MongoDB 中数据库的选择、创建与删除操作。使用 `use 数据库名称` 可选择或创建数据库,若数据库不存在则自动创建。通过 `show dbs` 或 `show databases` 查看所有可访问的数据库,用 `db` 命令查看当前数据库。注意,集合仅在插入数据后才会真正创建。数据库命名需遵循 UTF-8 格式,避免特殊字符,长度不超过 64 字节,且部分名称如 `admin`、`local` 和 `config` 为系统保留。删除数据库可通过 `db.dropDatabase()` 实现,主要用于移除已持久化的数据库。
424 0
|
6月前
|
存储 NoSQL 关系型数据库
微服务——MongoDB简介和体系结构
MongoDB是一种开源、高性能的文档型数据库,采用无模式设计,数据结构灵活,以类似JSON的BSON格式存储。它将记录作为文档,由字段和值对组成,支持复杂数据类型及嵌套结构。相比MySQL,MongoDB去除了传统表结构,使用集合(Collection)存储文档,适合处理非结构化和半结构化数据,简化开发并提升扩展性。其架构更灵活,适用于高并发和大数据场景。
427 0
|
6月前
|
JSON NoSQL 关系型数据库
MongoDB简介
MongoDB是一个开源、高性能、无模式的文档型数据库,当初的设计就是用于简化开发和方便扩展,是NoSQL数据库产品中的一种。是最像关系型数据库(MySQL)的非关系型数据库。 它支持的数据结构非常松散,是一种类似于 JSON 的格式叫BSON,所以它既可以存储比较复杂的数据类型,又相当的灵活。 MongoDB中的记录是一个文档,它是一个由字段和值对(field:value)组成的数据结构。MongoDB文档类似于JSON对象,即一个文档认为就是一个对象。字段的数据类型是字符型,它的值除了使用基本的一些类型外,还可以包括其他文档、普通数组和文档数组。

推荐镜像

更多