开始:
Mongo Shell
安装后,输入mongo进入控制台:
//所有帮助 > help //数据库的方法 > db.help() > db.stats() //当前数据库的状态,包括collections属性,显示有多少个。 > show dbs //显示所有的数据库
Insert Document
使用控制台insert和执行查询语法:
db.inventory.insertMany({
{ item: "journal", qty: 25, status: "A", size: { h: 14, w: 21, uom: "cm" }, tags: [ "blank", "red" ] }
})
db.collection.insertOne()
Query Document
例子:
db.inventory.find({status: "D"})
查询嵌套属性: "field.field": value
db.inventory.find( { "size.uom": "cm" } )
查询在数组中的一个元素: filed:value之一
db.inventory.find({tags: "red"})
查询一个数组:
db.inventory.find( { tags: ["red", "blank"] } )
Databases and Collections
MongoDB在collections内存储数据记录,BSON documents等;
collections则存在于数据库内。
Database
选择一个数据库:
use myDB
创建一个数据库
use myNewDB db.myNewCollection1.insertOne({x: 1})
解释:
如果myNewDB不存在,当你第一次向这个数据库存入数据时,就会创建这个数据库。
因此,你可以使用use方法切换到一个不存在的数据库,然后执行插入数据的操作,在mongo shell.
insertOne方法创建了数据库myNewDB,同时也创建了collection: myNewCollection1(如果它们不存在)
Collections
MongoDB在collections内存储documents。
collections 类似关系数据库的table。
//如果collection不存在,则第一次存入数据时创建它。 db.myNewCollection2.insertOne({ x: 1})
明确的创建
主要用于设置一些选项。
// 明确创建一个collection // 可以设置一些选项:最大的size, documentation validatin rules。 // 如果你不指定这些选项,就没必要使用这个方法了 db.createCollection()
Document Validation(version3.2新功能)
一般来说collection无需要它的documents有相同的结构。
即在一个collection内,documents不需要有相同的fields和数据类型。
mongoDB是一个非关系性的数据库。
但,3.2version 增加了这个验证功能See Schema Validation for details.
修改Document Structure
可以改变一个collection内的documents的结构,包括增加新fields, remove fields,或者改变field的值。
Views(new in version3.4)
支持创建只读的views。 从existing collections或者其他views创建。
Documents
相当于关系型数据库的每条记录。
MongoDB储存数据记录的格式是 BSON.
BSON is a binary representation of JSON documents, 比JSON的数据类型多。
See also BSON Types.
{
field1: value1,
field2: value2,
field3: value3,
...
fieldN: valueN
}
一个filed的值可以是任何形式的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) }
contribes是array of strings的数据类型。
filed names是字符串, 不能有null, 顶级的filed name不能以$开始
Dot标记
MongoDB使用dot来存取一个array的元素, 或者一个嵌套的document(hash)的field。
BSON Types
https://docs.mongodb.com/manual/reference/bson-types/