mongodb使用BSON格式存儲數據記錄. 以下圖:html
文檔有鍵值對組成, 有如下結構:sql
{
field1: value1,
field2: value2,
...
fieldN: valueN
}mongodb
字段的值能夠是任意BSON 數據類型,包括其餘文檔, 數組和文檔數組.數組
例如,如下文檔包含不一樣類型的值:服務器
{
_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)
}app
解析:spa
_id
是 ObjectId類型.name
值是一個嵌入的文檔,包含字段 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.字段名是String類型翻譯
文檔在字段名上有如下限制:3d
_id
保留用做主鍵; 它的值在集合中必須是惟一的,是不可變的,而且能夠是除數組之外的任何類型。有時候bson 文檔可能有多個字段使用同一個名字.這種狀況,參考:driver documentation .code
對於索引集合,索引字段的值具備最大索引鍵長度限制。 有關詳細信息, SeeMaximum Index Key Length
。
MongoDB使用點符號來訪問數組的元素並訪問嵌入文檔的字段。
要經過基於零的索引位置指定或訪問數組的元素,請將數組名稱與點(.)和從零開始的索引位置鏈接起來,並用引號引發來:
"<array>.<index>"
{
...
contribs: [ "Turing machine", "Turing test", "Turingery" ],
...
}
要訪問第三個字符:"contribs.2"
.
For examples querying arrays, see:
要使用點符號指定或訪問嵌入式文檔的字段,使用如下格式: 嵌入文檔名稱.字段名:
"<embedded document>.<field>"
{
...
name: { first: "Alan", last: "Turing" },
contact: { phone: { type: "cell", number: "111-222-3333" } },
...
}
上邊的 name, contact,以及嵌入在contact裏邊的phone都是嵌入式文檔.
指定name字段中的last : "name.last"
.
在contact 中指定phone的號碼: "contact.phone.number"
.
For examples querying embedded documents, see:
Documents有如下屬性:
bson文檔的最大值是16M.
最大的文檔大小有助於確保單個文檔不能使用過多的RAM,或者在傳輸過程當中使用過多的帶寬。 爲了存儲大於最大大小的文檔,MongoDB提供了GridFS API。 有關GridFS的更多信息,請參閱mongofiles和驅動程序的文檔。
除如下狀況外,MongoDB保留寫入操做以後的文檔字段的順序:
_id
永遠是文檔的第一個字段renaming
字段名可能會致使字段重排序._id
Field在MongoDB中,存儲在集合中的每一個文檔都須要一個惟一的_id字段做爲主鍵。 若是插入的文檔省略_id字段,則MongoDB驅動程序自動爲_id字段生成一個ObjectId。
_id字段有如下行爲和約束:
_id值的經常使用選項:
除了定義數據記錄以外,MongoDB還一直使用文檔結構,包括但不限於:query filters, update specifications documents, and index specification documents.
查詢過濾器指定紀錄被選中的條件.
你可使用<field>:<value> 表達式指定相等條件和查詢運算符表達式。
{
<field1>: <value1>,
<field2>: { <operator>: <value> },
...
}
For examples, see:
舉一個Query Documents的例子:
db.inventory.find( { status: "D" } )
inventory
集合中找出status = "D"的記錄. 與sql 中的語句一致:
SELECT * FROM inventory WHERE status = "D"
查詢過濾器文檔可使用查詢運算符來指定如下形式的條件:
{ <field1>: { <operator1>: <value1> }, ... }
下邊的例子展現從inventory
集合中檢索 status等於"A"或"D"的記錄.
db.inventory.find( { status: { $in: [ "A", "D" ] } } )
這個語句與下邊sql的語句一致:
SELECT * FROM inventory WHERE status in ("A", "D")
還有and 和or 的用法,想看的看這個文檔Query Documents.
更新文檔使用update operators 來指定在db.collection.update() 操做期間在指定字段上執行的數據修改。
{
<operator1>: { <field1>: <value1>, ... },
<operator2>: { <field2>: <value2>, ... },
...
}
For examples, see Update specifications.
索引規範文檔定義字段索引和索引類型:
{ <field1>: <type1>, <field2>: <type2>, ... }
翻譯自官網: https://docs.mongodb.com/manual/core/document/