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/