文檔 (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將數(shù)據(jù)記錄存儲(chǔ)為BSON文檔刨晴。BSON是JSON文檔的二進(jìn)制表示介牙,但包含比JSON更多的數(shù)據(jù)類(lèi)型房待。

文檔結(jié)構(gòu)

MongoDB文檔由字段和值對(duì)組成柬脸,并具有以下結(jié)構(gòu):

{ 
   field1 : value1 ,
   field2 : value2 妄均,
   field3 : value3 柱锹,
   ... 
   fieldN : valueN 
}

字段的值可以是任何BSON 數(shù)據(jù)類(lèi)型,包括其他文檔丰包,數(shù)組和文檔數(shù)組禁熏。例如,以下文檔包含不同類(lèi)型的值:

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)
            }

以上字段具有以下數(shù)據(jù)類(lèi)型:

  • _id擁有一個(gè)ObjectId邑彪。
  • name擁有包含字段和內(nèi)容的 嵌入式文檔瞧毙。
  • birthdeath保存日期類(lèi)型的值。
  • contribs擁有一個(gè)字符串?dāng)?shù)組锌蓄。
  • views保存NumberLong類(lèi)型的值升筏。

字段名稱(chēng)

字段名稱(chēng)是字符串。
文檔對(duì)字段名稱(chēng)有以下限制:

  • 字段名稱(chēng)_id被保留用作主鍵; 它的值在集合中必須是唯一的瘸爽,是不可變的,并且可以是除數(shù)組以外的任何類(lèi)型铅忿。
  • 字段名稱(chēng)不能以美元符號(hào)($)字符開(kāi)頭剪决。
  • 字段名稱(chēng)不能包含dot(.)字符。
  • 字段名稱(chēng)不能包含null字符

BSON文檔可能有多個(gè)同名的字段。然而柑潦,大多數(shù)的MongoDB接口代表MongoDB的結(jié)構(gòu)(如哈希表)享言,不支持重復(fù)的字段名稱(chēng)。如果您需要操作具有多個(gè)具有相同名稱(chēng)的字段的文檔渗鬼,請(qǐng)參閱驅(qū)動(dòng)程序的驅(qū)動(dòng)程序文檔览露。

通過(guò)內(nèi)部的MongoDB進(jìn)程創(chuàng)建的有些文件可能有重復(fù)的字段,但是沒(méi)有 MongoDB的過(guò)程中會(huì)不斷地添加重復(fù)字段到現(xiàn)有的用戶(hù)文檔譬胎。

對(duì)于索引集合差牛,索引字段的值有一個(gè)最大索引鍵長(zhǎng)度限制。有關(guān)詳細(xì)信息堰乔,請(qǐng)參見(jiàn)最大索引鍵長(zhǎng)度偏化。

字段值限制

對(duì)于索引集合,索引字段的值有一個(gè)最大索引鍵長(zhǎng)度限制镐侯。有關(guān)詳細(xì)信息侦讨,請(qǐng)參見(jiàn)最大索引鍵長(zhǎng)度。

點(diǎn)符號(hào)

MongoDB使用點(diǎn)符號(hào)來(lái)訪(fǎng)問(wèn)數(shù)組的元素并訪(fǎng)問(wèn)嵌入文檔的字段苟翻。

數(shù)組

要通過(guò)基于零的索引位置來(lái)指定或訪(fǎng)問(wèn)數(shù)組的元素韵卤,請(qǐng)將數(shù)組名與dot(.)和從零開(kāi)始的索引位置連接起來(lái),并用引號(hào)括起來(lái):

"<array>.<index>"

例如崇猫,在文檔中給出以下字段:

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

要指定contribs數(shù)組中的第三個(gè)元素沈条,請(qǐng)使用點(diǎn)符號(hào)"contribs.2"

有關(guān)查詢(xún)數(shù)組的示例邓尤,請(qǐng)參見(jiàn):

也可以看看

  • $[] 所有更新操作的位置操作員拍鲤,
  • $[/<identifier/>] 過(guò)濾位置運(yùn)算符用于更新操作,
  • $ 更新操作的位置操作員汞扎,
  • $ 數(shù)組索引位置未知時(shí)的投影算子
  • 使用數(shù)組查詢(xún)數(shù)組的點(diǎn)符號(hào)示例季稳。

嵌入式文件

要用點(diǎn)符號(hào)指定或訪(fǎng)問(wèn)嵌入式文檔的字段,請(qǐng)將嵌入式文檔名稱(chēng)與dot(.)和字段名稱(chēng)連接起來(lái)澈魄,并用引號(hào)括起來(lái):

"<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字段景鼠,請(qǐng)使用點(diǎn)符號(hào)"name.last"
  • 要在字段number中的phone文檔中 指定contact痹扇,請(qǐng)使用點(diǎn)符號(hào)"contact.phone.number"铛漓。

有關(guān)查詢(xún)嵌入式文檔的示例,請(qǐng)參閱:

文件限制

文檔具有以下屬性:

文件大小限制

最大的BSON文檔大小是16兆字節(jié)鲫构。

最大的文檔大小有助于確保單個(gè)文檔不能使用過(guò)多的RAM浓恶,或者在傳輸過(guò)程中使用過(guò)多的帶寬。為了存儲(chǔ)大于最大大小的文檔结笨,MongoDB提供了GridFS API包晰。有關(guān)GridFS的更多信息湿镀,請(qǐng)參閱mongofiles驅(qū)動(dòng)程序的文檔。

文檔字段順序

以下情況伐憾,MongoDB保留寫(xiě)入操作之后的文檔字段的順序:

  • _id字段始終是文檔中的第一個(gè)字段勉痴。
  • 包含renaming字段名稱(chēng)的更新可能會(huì)導(dǎo)致文檔中字段的重新排序。

在版本2.6中更改:從版本2.6開(kāi)始树肃,MongoDB主動(dòng)嘗試保留文檔中的字段順序蒸矛。在版本2.6之前,MongoDB沒(méi)有主動(dòng)保留文檔中字段的順序胸嘴。

字段 _id

在MongoDB中雏掠,存儲(chǔ)在集合中的每個(gè)文檔都需要一個(gè)唯一的 _id字段作為主鍵。如果插入的文檔省略了該_id字段筛谚,那么MongoDB驅(qū)動(dòng)程序?qū)⒆詣?dòng)為該字段生成一個(gè)ObjectId_id磁玉。

這也適用于使用upsert:true通過(guò)更新操作插入的文檔。

_id領(lǐng)域有以下行為和約束:

  • 默認(rèn)情況下驾讲,MongoDB _id在創(chuàng)建集合的時(shí)候在字段上創(chuàng)建一個(gè)唯一索引蚊伞。
  • _id字段始終是文檔中的第一個(gè)字段。如果服務(wù)器收到一個(gè)沒(méi)有_id第一個(gè)字段的文檔吮铭,那么服務(wù)器將把這個(gè)字段移到開(kāi)頭时迫。
  • _id字段可能包含除數(shù)組以外的任何BSON數(shù)據(jù)類(lèi)型的值。

警告
為確保功能復(fù)制谓晌,請(qǐng)不要在_id 字段中存儲(chǔ)具有BSON正則表達(dá)式類(lèi)型的值掠拳。

以下是用于存儲(chǔ)以下值的常用選項(xiàng)_id

  • 使用一個(gè)ObjectId

  • 使用自然唯一標(biāo)識(shí)符(如果可用)纸肉。這節(jié)省了空間并避免了額外的索引溺欧。

  • 生成一個(gè)自動(dòng)遞增的數(shù)字。

  • 在您的應(yīng)用程序代碼中生成一個(gè)UUID柏肪。為了更高效地存儲(chǔ)集合中和_id 索引中的UUID值姐刁,請(qǐng)將UUID存儲(chǔ)為BSON BinData類(lèi)型的值。

    如果滿(mǎn)足以下條件烦味,索引鍵BinData將更有效地存儲(chǔ)在索引中:

    • 二進(jìn)制子類(lèi)型的值在0-7或128-135的范圍內(nèi)
    • 字節(jié)數(shù)組的長(zhǎng)度為:0,1,2,3,4,5,6,7,8,10,12,14,16,20,24或32聂使。
  • 使用您的驅(qū)動(dòng)程序的BSON UUID工具來(lái)生成UUID。請(qǐng)注意谬俄,驅(qū)動(dòng)程序?qū)崿F(xiàn)可能會(huì)以不同的方式實(shí)現(xiàn)UUID序列化和反序列化邏輯柏靶,這可能與其他驅(qū)動(dòng)程序不完全兼容。有關(guān)UUID互操作性的信息溃论,請(qǐng)參閱您的驅(qū)動(dòng)程序文檔

注意
大多數(shù)MongoDB驅(qū)動(dòng)程序客戶(hù)端將包含該_id字段并ObjectId在將插入操作發(fā)送到MongoDB之前生成一個(gè)字段; 然而屎蜓,如果客戶(hù)端發(fā)送的文件沒(méi)有一個(gè)_id 字段,mongod將會(huì)添加_id字段并生成ObjectId钥勋。

文檔結(jié)構(gòu)的其他用途

除了定義數(shù)據(jù)記錄之外梆靖,MongoDB還一直使用文檔結(jié)構(gòu)控汉,包括但不限于:查詢(xún)過(guò)濾器笔诵,更新規(guī)范文檔索引規(guī)范文檔

查詢(xún)文檔篩選

查詢(xún)過(guò)濾器文檔指定確定要為讀取返吻,更新和刪除操作選擇哪些記錄的條件。

您可以使用<field>:<value>表達(dá)式來(lái)指定相等條件和查詢(xún)運(yùn)算符 表達(dá)式乎婿。

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

For examples, see:

更新規(guī)范文件

更新規(guī)范文檔使用更新操作符來(lái)指定在db.collection.update()操作期間在特定字段上執(zhí)行的數(shù)據(jù)修改测僵。

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

有關(guān)示例,請(qǐng)參閱更新規(guī)范谢翎。

索引規(guī)范文件

索引規(guī)范文件定義字段索引和索引類(lèi)型:

{ <field1>: <type1>, <field2>: <type2>, ...  }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末捍靠,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子森逮,更是在濱河造成了極大的恐慌榨婆,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,744評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件褒侧,死亡現(xiàn)場(chǎng)離奇詭異良风,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)闷供,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,505評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén)烟央,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人歪脏,你說(shuō)我怎么就攤上這事疑俭。” “怎么了婿失?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,105評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵钞艇,是天一觀(guān)的道長(zhǎng)。 經(jīng)常有香客問(wèn)我豪硅,道長(zhǎng)哩照,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,242評(píng)論 1 292
  • 正文 為了忘掉前任舟误,我火速辦了婚禮葡秒,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘嵌溢。我一直安慰自己眯牧,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,269評(píng)論 6 389
  • 文/花漫 我一把揭開(kāi)白布赖草。 她就那樣靜靜地躺著学少,像睡著了一般。 火紅的嫁衣襯著肌膚如雪秧骑。 梳的紋絲不亂的頭發(fā)上版确,一...
    開(kāi)封第一講書(shū)人閱讀 51,215評(píng)論 1 299
  • 那天扣囊,我揣著相機(jī)與錄音,去河邊找鬼绒疗。 笑死侵歇,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的吓蘑。 我是一名探鬼主播惕虑,決...
    沈念sama閱讀 40,096評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼磨镶!你這毒婦竟也來(lái)了溃蔫?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 38,939評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤琳猫,失蹤者是張志新(化名)和其女友劉穎伟叛,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體脐嫂,經(jīng)...
    沈念sama閱讀 45,354評(píng)論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡统刮,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,573評(píng)論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了雹锣。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片网沾。...
    茶點(diǎn)故事閱讀 39,745評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖蕊爵,靈堂內(nèi)的尸體忽然破棺而出辉哥,到底是詐尸還是另有隱情,我是刑警寧澤攒射,帶...
    沈念sama閱讀 35,448評(píng)論 5 344
  • 正文 年R本政府宣布醋旦,位于F島的核電站,受9級(jí)特大地震影響会放,放射性物質(zhì)發(fā)生泄漏饲齐。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,048評(píng)論 3 327
  • 文/蒙蒙 一咧最、第九天 我趴在偏房一處隱蔽的房頂上張望捂人。 院中可真熱鬧,春花似錦矢沿、人聲如沸滥搭。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,683評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)瑟匆。三九已至,卻和暖如春栽惶,著一層夾襖步出監(jiān)牢的瞬間愁溜,已是汗流浹背疾嗅。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,838評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留冕象,地道東北人代承。 一個(gè)月前我還...
    沈念sama閱讀 47,776評(píng)論 2 369
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像交惯,于是被迫代替她去往敵國(guó)和親次泽。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,652評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • 得知喬白與和白喬與是親姐弟后席爽,除了顧城懌和任何,其他那幾個(gè)都看起來(lái)特別郁悶啊片,特別是簡(jiǎn)陽(yáng)只锻,直播的時(shí)候還和粉絲發(fā)牢騷:...
    玩核桃的大爺閱讀 366評(píng)論 0 2
  • 心靈對(duì)話(huà).寫(xiě)作小組第12篇 今天所有工作基本完成,松了口氣紫谷,明天老爸過(guò)生日齐饮,今天下班與老公一起提前去看他,跟弟弟一...
    美麗的小魚(yú)閱讀 174評(píng)論 0 0
  • 第一更 漩渦 仁川市笤昨,仕蘭中學(xué)祖驱,課間。 深吸一口氣瞒窒,蘇展鼓起勇氣走向那個(gè)他已經(jīng)心動(dòng)了好久的女生——駱祺寒捺僻。她是...
    only_rain閱讀 679評(píng)論 0 0