您的位置:首页 > 数据库 > Mongodb

MongoDB模型

2016-01-30 18:16 357 查看
实现了关系型模型的数据库就称为关系型数据库。关系型模型简单的说,就是由一系列的tuples(rows),以及tuples之间的关系构成。

具体到关系型数据库,该模型的表现形式就是结构相同的rows(即符合同一种schema)被组织到一个table中,而不同的table之间用外键关联。从本质上说,外键反应的是不同table间的row的关系而不是table之间的关系。而我们对关系型数据库的操作其实就是对tuples的操作–增加,修改或返回rows。

而NOSQL数据库则不再使用关系型模型,且不同的NOSQL数据库使用不同的模型。基本可以分为4类:



本文涉及的是MongoDB对关系型模型的支持,因为在使用MongoDB时,我们很自然的想知道它对传统的关系型模式的支持,从而决定是否应该使用这种数据库。

这里仅仅涉及关系型数据库中的几个方面。关于更详细的MongoDB的设计问题,可以参考一本书“Document Design for MongoDB”。

MongoDB和关系型数据库的术语对比

首先来看看MongoDB中一行数据的样子(也就是document):

{

_id: ObjectId(“509a8fb2f3f4948bd2f983a0”),

user_id: “abc123”,

age: 55,

status: ‘A’

}



事务

MongoDB does not have support for traditional locking or complex transactions with rollback. MongoDB aims to be lightweight, fast, and predictable in its performance. This is similar to the MySQL MyISAM autocommit model. By keeping transaction support extremely simple, MongoDB can provide greater performance especially for partitioned or replicated systems with a number of database server processes.

MongoDB does have support for atomic operations within a single document. Given the possibilities provided by nested documents, this feature provides support for a large number of use-cases.

外键和Join

从上文可以知道,外键和join其实都是关系型模型的要素。关系型数据库的“设计模式”:范式所讲述的就是如何正确的组织数据,以便最小化冗余并消除数据异常。一个范式化的数据库必然涉及外键和join。而NOSQL不再使用关系型模型,因而外键和join不再是必然。但是由于某些商业原因,一些NOSQL数据库支持部分功能。

MongoDB doesn’t support server side foreign key relationships, normalization is also discouraged. so there is a special construct called DBRef which allows to reference objects in a different collection.

MongoDB doesn’t support join.

If your schema is more complex then probably your should choose a relational database and not nosql. 如上图中,SQL“table joins”对应MongoDB“embedded documents and linking”所示,MongoDB建议将所有相关的field都放到嵌套的document中,而不是关系型数据库那样分散到多个表中。

索引

MongoDB使用索引来提高查询效率。索引使用的数据结构和关系型数据库相同,也是B-tree的。如上图所示,支持主键,但用户不能指定,自动为_ID列。

Aggregation

下面是MongoDB实现的aggregation列表:



下面是使用示例:

https://docs.mongodb.org/manual/reference/sql-aggregation-comparison/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: