0On this page
- 文档结构 Document Structure
- 点符号 Dot Notation
- 文档的限制 Document Limitations
- 文档结构的其他用途 Other Uses of the Document Structure
- 其他资源 Additional Resources
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 fieldsfirst
andlast
. -
birth
anddeath
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:
"."
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:
- Query an Array
- Query an Array of Embedded Documents
SEE ALSO
-
$[]
all positional operator for update operations, -
$[/
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:
"."
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 thename
field, use the dot notation"name.last"
. - To specify the
number
in thephone
document in thecontact
field, use the dot notation"contact.phone.number"
.
For examples querying embedded documents, see:
- Query on Embedded/Nested Documents
- Query an Array of Embedded Documents
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 _id
field.
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 BSONBinData
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 anObjectId
before sending the insert operation to MongoDB; however, if the client sends a document without an_id
field, themongod
will add the_id
field and generate theObjectId
.
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
expressions to specify the equality condition and query operatorexpressions.
{
: ,
: { : },
...
}
For examples, see:
- Query Documents
- Query on Embedded/Nested Documents
- Query an Array
- Query an Array of Embedded Documents
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.
{
: { : , ... },
: { : , ... },
...
}
For examples, see Update specifications.
Index Specification Documents
Index specifications document define the field to index and the index type:
{ : , : , ... }
Additional Resources
- Thinking in Documents Part 1 (Blog Post)
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
拥有包含字段和内容的 嵌入式文档。 -
birth
并death
保存日期类型的值。 -
contribs
拥有一个字符串数组。 -
views
保存NumberLong类型的值。
字段名称
字段名称是字符串。
文档对字段名称有以下限制:
- 字段名称
_id
被保留用作主键; 它的值在集合中必须是唯一的,是不可变的,并且可以是除数组以外的任何类型。 - 字段名称不能以美元符号(
$
)字符开头。 - 字段名称不能包含dot(
.
)字符。 - 字段名称不能包含
null
字符
BSON文档可能有多个同名的字段。然而,大多数的MongoDB接口代表MongoDB的结构(如哈希表),不支持重复的字段名称。如果您需要操作具有多个具有相同名称的字段的文档,请参阅驱动程序的驱动程序文档。
通过内部的MongoDB进程创建的有些文件可能有重复的字段,但是没有 MongoDB的过程中会不断地添加重复字段到现有的用户文档。
对于索引集合,索引字段的值有一个最大索引键长度限制。有关详细信息,请参见最大索引键长度。
字段值限制
对于索引集合,索引字段的值有一个最大索引键长度限制。有关详细信息,请参见最大索引键长度。
点符号
MongoDB使用点符号来访问数组的元素并访问嵌入文档的字段。
数组
要通过基于零的索引位置来指定或访问数组的元素,请将数组名与dot(.
)和从零开始的索引位置连接起来,并用引号括起来:
"."
例如,在文档中给出以下字段:
{
...
contribs: [ "Turing machine", "Turing test", "Turingery" ],
...
}
要指定contribs
数组中的第三个元素,请使用点符号"contribs.2"
。
有关查询数组的示例,请参见:
- 查询数组
- 查询嵌入式文档数组
也可以看看
-
$[]
所有更新操作的位置操作员, -
$[/
过滤位置运算符用于更新操作,] -
$
更新操作的位置操作员, -
$
数组索引位置未知时的投影算子 - 使用数组查询数组的点符号示例。
嵌入式文件
要用点符号指定或访问嵌入式文档的字段,请将嵌入式文档名称与dot(.
)和字段名称连接起来,并用引号括起来:
"."
For example, given the following field in a document:
{
...
name: { first: "Alan", last: "Turing" },
contact: { phone: { type: "cell", number: "111-222-3333" } },
...
}
- 要指定字段中指定
last
的name
字段,请使用点符号"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存储为BSONBinData
类型的值。如果满足以下条件,索引键
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还一直使用文档结构,包括但不限于:查询过滤器,更新规范文档和索引规范文档
查询文档筛选
查询过滤器文档指定确定要为读取,更新和删除操作选择哪些记录的条件。
您可以使用
表达式来指定相等条件和查询运算符 表达式。
{
: ,
: { : },
...
}
For examples, see:
- Query Documents
- Query on Embedded/Nested Documents
- Query an Array
- Query an Array of Embedded Documents
更新规范文件
更新规范文档使用更新操作符来指定在db.collection.update()
操作期间在特定字段上执行的数据修改。
{
: { : , ... },
: { : , ... },
...
}
有关示例,请参阅更新规范。
索引规范文件
索引规范文件定义字段索引和索引类型:
{ : , : , ... }