文档 (Documents)

0On this page

MongoDB stores data records as BSON documents. BSON is a binary representation of JSON documents, though it contains more data types than JSON. For the BSON spec, see bsonspec.org. See also BSON Types.

Document Structure

MongoDB documents are composed of field-and-value pairs and have the following structure:

{ 
   field1 : value1 ,
   field2 : value2 ,
   field3 : value3 ,
   ... 
   fieldN : valueN 
}

The value of a field can be any of the BSON data types, including other documents, arrays, and arrays of documents. For example, the following document contains values of varying types:

var mydoc = {
               _id: ObjectId("5099803df3f4948bd2f98391"),
               name: { first: "Alan", last: "Turing" },
               birth: new Date('Jun 23, 1912'),
               death: new Date('Jun 07, 1954'),
               contribs: [ "Turing machine", "Turing test", "Turingery" ],
               views : NumberLong(1250000)
            }

The above fields have the following data types:

  • _id holds an ObjectId.
  • name holds an embedded document that contains the fields first and last.
  • birth and death hold values of the Date type.
  • contribs holds an array of strings.
  • views holds a value of the NumberLong type.

Field Names

Field names are strings.

Documents have the following restrictions on field names:

  • The field name _id is reserved for use as a primary key; its value must be unique in the collection, is immutable, and may be of any type other than an array.
  • The field names cannot start with the dollar sign ($) character.
  • The field names cannot contain the dot (.) character.
  • The field names cannot contain the null character.

BSON documents may have more than one field with the same name. Most MongoDB interfaces, however, represent MongoDB with a structure (e.g. a hash table) that does not support duplicate field names. If you need to manipulate documents that have more than one field with the same name, see the driver documentation for your driver.

Some documents created by internal MongoDB processes may have duplicate fields, but no MongoDB process will ever add duplicate fields to an existing user document.

Field Value Limit

For indexed collections, the values for the indexed fields have a Maximum Index Key Length limit. SeeMaximum Index Key Length for details.

Dot Notation

MongoDB uses the dot notation to access the elements of an array and to access the fields of an embedded document.

Arrays

To specify or access an element of an array by the zero-based index position, concatenate the array name with the dot (.) and zero-based index position, and enclose in quotes:

"<array>.<index>"

For example, given the following field in a document:

{
   ...
   contribs: [ "Turing machine", "Turing test", "Turingery" ],
   ...
}

To specify the third element in the contribs array, use the dot notation "contribs.2".

For examples querying arrays, see:

SEE ALSO

  • $[] all positional operator for update operations,
  • $[/<identifier/>] filtered positional operator for update operations,
  • $ positional operator for update operations,
  • $ projection operator when array index position is unknown
  • Query an Array for dot notation examples with arrays.

Embedded Documents

To specify or access a field of an embedded document with dot notation, concatenate the embedded document name with the dot (.) and the field name, and enclose in quotes:

"<embedded document>.<field>"

For example, given the following field in a document:

{
   ...
   name: { first: "Alan", last: "Turing" },
   contact: { phone: { type: "cell", number: "111-222-3333" } },
   ...
}
  • To specify the field named last in the name field, use the dot notation "name.last".
  • To specify the number in the phone document in the contact field, use the dot notation "contact.phone.number".

For examples querying embedded documents, see:

Document Limitations

Documents have the following attributes:

Document Size Limit

The maximum BSON document size is 16 megabytes.

The maximum document size helps ensure that a single document cannot use excessive amount of RAM or, during transmission, excessive amount of bandwidth. To store documents larger than the maximum size, MongoDB provides the GridFS API. See mongofiles and the documentation for your driver for more information about GridFS.

Document Field Order

MongoDB preserves the order of the document fields following write operations except for the following cases:

  • The _id field is always the first field in the document.
  • Updates that include renaming of field names may result in the reordering of fields in the document.

Changed in version 2.6: Starting in version 2.6, MongoDB actively attempts to preserve the field order in a document. Before version 2.6, MongoDB did not actively preserve the order of the fields in a document.

The _id Field

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _idfield.

This also applies to documents inserted through update operations with upsert: true.

The _id field has the following behavior and constraints:

  • By default, MongoDB creates a unique index on the _id field during the creation of a collection.

  • The _id field is always the first field in the documents. If the server receives a document that does not have the _id field first, then the server will move the field to the beginning.

  • The _id field may contain values of any BSON data type, other than an array.

WARNING
To ensure functioning replication, do not store values that are of the BSON regular expression type in the _id field.

The following are common options for storing values for _id:

  • Use an ObjectId.

  • Use a natural unique identifier, if available. This saves space and avoids an additional index.

  • Generate an auto-incrementing number.

  • Generate a UUID in your application code. For a more efficient storage of the UUID values in the collection and in the _id index, store the UUID as a value of the BSON BinData type.

    Index keys that are of the BinData type are more efficiently stored in the index if:

    • the binary subtype value is in the range of 0-7 or 128-135, and
    • the length of the byte array is: 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, or 32.
  • Use your driver’s BSON UUID facility to generate UUIDs. Be aware that driver implementations may implement UUID serialization and deserialization logic differently, which may not be fully compatible with other drivers. See your driver documentation for information concerning UUID interoperability.

NOTE
Most MongoDB driver clients will include the _id field and generate an ObjectId before sending the insert operation to MongoDB; however, if the client sends a document without an _id field, the mongodwill add the _id field and generate the ObjectId.

Other Uses of the Document Structure

In addition to defining data records, MongoDB uses the document structure throughout, including but not limited to: query filters, update specifications documents, and index specification documents

Query Filter Documents

Query filter documents specify the conditions that determine which records to select for read, update, and delete operations.

You can use <field>:<value> expressions to specify the equality condition and query operatorexpressions.

{
  <field1>: <value1>,
  <field2>: { <operator>: <value> },
  ...
}

For examples, see:

Update Specification Documents

Update specification documents use update operators to specify the data modifications to perform on specific fields during an db.collection.update() operation.

{
  <operator1>: { <field1>: <value1>, ... },
  <operator2>: { <field2>: <value2>, ... },
  ...
}

For examples, see Update specifications.

Index Specification Documents

Index specifications document define the field to index and the index type:

{ <field1>: <type1>, <field2>: <type2>, ...  }

Additional Resources

MongoDB将数据记录存储为BSON文档。BSON是JSON文档的二进制表示,但包含比JSON更多的数据类型。

文档结构

MongoDB文档由字段和值对组成,并具有以下结构:

{ 
   field1 : value1 ,
   field2 : value2 ,
   field3 : value3 ,
   ... 
   fieldN : valueN 
}

字段的值可以是任何BSON 数据类型,包括其他文档,数组和文档数组。例如,以下文档包含不同类型的值:

var mydoc = {
               _id: ObjectId("5099803df3f4948bd2f98391"),
               name: { first: "Alan", last: "Turing" },
               birth: new Date('Jun 23, 1912'),
               death: new Date('Jun 07, 1954'),
               contribs: [ "Turing machine", "Turing test", "Turingery" ],
               views : NumberLong(1250000)
            }

以上字段具有以下数据类型:

  • _id拥有一个ObjectId
  • name拥有包含字段和内容的 嵌入式文档。
  • birthdeath保存日期类型的值。
  • contribs拥有一个字符串数组
  • views保存NumberLong类型的值。

字段名称

字段名称是字符串。
文档对字段名称有以下限制:

  • 字段名称_id被保留用作主键; 它的值在集合中必须是唯一的,是不可变的,并且可以是除数组以外的任何类型。
  • 字段名称不能以美元符号($)字符开头。
  • 字段名称不能包含dot(.)字符。
  • 字段名称不能包含null字符

BSON文档可能有多个同名的字段。然而,大多数的MongoDB接口代表MongoDB的结构(如哈希表),不支持重复的字段名称。如果您需要操作具有多个具有相同名称的字段的文档,请参阅驱动程序的驱动程序文档

通过内部的MongoDB进程创建的有些文件可能有重复的字段,但是没有 MongoDB的过程中会不断地添加重复字段到现有的用户文档。

对于索引集合,索引字段的值有一个最大索引键长度限制。有关详细信息,请参见最大索引键长度。

字段值限制

对于索引集合,索引字段的值有一个最大索引键长度限制。有关详细信息,请参见最大索引键长度。

点符号

MongoDB使用点符号来访问数组的元素并访问嵌入文档的字段。

数组

要通过基于零的索引位置来指定或访问数组的元素,请将数组名与dot(.)和从零开始的索引位置连接起来,并用引号括起来:

"<array>.<index>"

例如,在文档中给出以下字段:

{
   ...
   contribs: [ "Turing machine", "Turing test", "Turingery" ],
   ...
}

要指定contribs数组中的第三个元素,请使用点符号"contribs.2"

有关查询数组的示例,请参见:

也可以看看

  • $[] 所有更新操作的位置操作员,
  • $[/<identifier/>] 过滤位置运算符用于更新操作,
  • $ 更新操作的位置操作员,
  • $ 数组索引位置未知时的投影算子
  • 使用数组查询数组的点符号示例。

嵌入式文件

要用点符号指定或访问嵌入式文档的字段,请将嵌入式文档名称与dot(.)和字段名称连接起来,并用引号括起来:

"<embedded document>.<field>"

For example, given the following field in a document:

{
   ...
   name: { first: "Alan", last: "Turing" },
   contact: { phone: { type: "cell", number: "111-222-3333" } },
   ...
}
  • 要指定字段中指定lastname字段,请使用点符号"name.last"
  • 要在字段number中的phone文档中 指定contact,请使用点符号"contact.phone.number"

有关查询嵌入式文档的示例,请参阅:

文件限制

文档具有以下属性:

文件大小限制

最大的BSON文档大小是16兆字节。

最大的文档大小有助于确保单个文档不能使用过多的RAM,或者在传输过程中使用过多的带宽。为了存储大于最大大小的文档,MongoDB提供了GridFS API。有关GridFS的更多信息,请参阅mongofiles驱动程序的文档。

文档字段顺序

以下情况,MongoDB保留写入操作之后的文档字段的顺序:

  • _id字段始终是文档中的第一个字段。
  • 包含renaming字段名称的更新可能会导致文档中字段的重新排序。

在版本2.6中更改:从版本2.6开始,MongoDB主动尝试保留文档中的字段顺序。在版本2.6之前,MongoDB没有主动保留文档中字段的顺序。

字段 _id

在MongoDB中,存储在集合中的每个文档都需要一个唯一的 _id字段作为主键。如果插入的文档省略了该_id字段,那么MongoDB驱动程序将自动为该字段生成一个ObjectId_id

这也适用于使用upsert:true通过更新操作插入的文档。

_id领域有以下行为和约束:

  • 默认情况下,MongoDB _id在创建集合的时候在字段上创建一个唯一索引。
  • _id字段始终是文档中的第一个字段。如果服务器收到一个没有_id第一个字段的文档,那么服务器将把这个字段移到开头。
  • _id字段可能包含除数组以外的任何BSON数据类型的值。

警告
为确保功能复制,请不要在_id 字段中存储具有BSON正则表达式类型的值。

以下是用于存储以下值的常用选项_id

  • 使用一个ObjectId

  • 使用自然唯一标识符(如果可用)。这节省了空间并避免了额外的索引。

  • 生成一个自动递增的数字。

  • 在您的应用程序代码中生成一个UUID。为了更高效地存储集合中和_id 索引中的UUID值,请将UUID存储为BSON BinData类型的值。

    如果满足以下条件,索引键BinData将更有效地存储在索引中:

    • 二进制子类型的值在0-7或128-135的范围内
    • 字节数组的长度为:0,1,2,3,4,5,6,7,8,10,12,14,16,20,24或32。
  • 使用您的驱动程序的BSON UUID工具来生成UUID。请注意,驱动程序实现可能会以不同的方式实现UUID序列化和反序列化逻辑,这可能与其他驱动程序不完全兼容。有关UUID互操作性的信息,请参阅您的驱动程序文档

注意
大多数MongoDB驱动程序客户端将包含该_id字段并ObjectId在将插入操作发送到MongoDB之前生成一个字段; 然而,如果客户端发送的文件没有一个_id 字段,mongod将会添加_id字段并生成ObjectId

文档结构的其他用途

除了定义数据记录之外,MongoDB还一直使用文档结构,包括但不限于:查询过滤器更新规范文档索引规范文档

查询文档筛选

查询过滤器文档指定确定要为读取,更新和删除操作选择哪些记录的条件。

您可以使用<field>:<value>表达式来指定相等条件和查询运算符 表达式。

{
  <field1>: <value1>,
  <field2>: { <operator>: <value> },
  ...
}

For examples, see:

更新规范文件

更新规范文档使用更新操作符来指定在db.collection.update()操作期间在特定字段上执行的数据修改。

{
  <operator1>: { <field1>: <value1>, ... },
  <operator2>: { <field2>: <value2>, ... },
  ...
}

有关示例,请参阅更新规范

索引规范文件

索引规范文件定义字段索引和索引类型:

{ <field1>: <type1>, <field2>: <type2>, ...  }
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,045评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,114评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,120评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,902评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,828评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,132评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,590评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,258评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,408评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,335评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,385评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,068评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,660评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,747评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,967评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,406评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,970评论 2 341

推荐阅读更多精彩内容

  • 得知乔白与和白乔与是亲姐弟后,除了顾城怿和任何,其他那几个都看起来特别郁闷,特别是简阳,直播的时候还和粉丝发牢骚:...
    玩核桃的大爷阅读 359评论 0 2
  • 心灵对话.写作小组第12篇 今天所有工作基本完成,松了口气,明天老爸过生日,今天下班与老公一起提前去看他,跟弟弟一...
    美丽的小鱼阅读 168评论 0 0
  • 第一更 漩涡 仁川市,仕兰中学,课间。 深吸一口气,苏展鼓起勇气走向那个他已经心动了好久的女生——骆祺寒。她是...
    only_rain阅读 663评论 0 0