Mongo CURD简介
1.使用use命令切换数据库
>use book
switched to db book
注意:book数据库可以不存在
2.在数据库中插入数据:
>db.towns.insert({name:"NewYork",population:2200,last_census:ISODate("1979-01- 10")})
WriteResult({ "nInserted" : 1 })
此时在towns表(mongodb中叫集合)中插入了一条记录(mongodb中叫文档),towns在插入之前也是可以不存在的。插入的记录是以JSON格式存在的。
3.查询数据库中的表或集合
> show collections
system.indexes
towns
4.使用find查询表中的记录
> db.towns.find()
{ "_id" : ObjectId("54c81ccf897304ea56300644"),
"name" : "New York",
"population" : 2200,
"last_census" : ISODate("1979-01-10T00:00:00Z") }
注意里面默认多了一个_id的列,该类型是ObjectId类型,类似一个自增的序列。它固定是12个字节,由时间戳、客户端机器ID、客户端进程ID和3个自增的字节。
5.更多对表的操作我们可以使用help命令
db.towns.find().help()
> db.towns.find().help()
find() modifiers
.sort( {...} )
.limit( n )
.skip( n )
.count(applySkipLimit) - total # of objects matching query. by default ignores skip,limit
.size() - total # of objects cursor would return, honors skip,limit
.explain([verbose])
.hint(...)
.addOption(n) - adds op_query options -- see wire protocol
._addSpecial(name, value) - http://dochub.mongodb.org/core/advancedqueries#AdvancedQueries-Metaqueryoperators
.batchSize(n) - sets the number of docs to return per getMore
.showDiskLoc() - adds a $diskLoc field to each returned object
.min(idxDoc)
.max(idxDoc)
.comment(comment)
.snapshot()
.readPref(mode, tagset)Cursor methods
.toArray() - iterates through docs and returns an array of the results
.forEach( func )
.map( func )
.hasNext()
.next()
.objsLeftInBatch() - returns count of docs left in current batch (when exhausted, a new getMore will be issued)
.itcount() - iterates through documents and counts them
.pretty() - pretty print each document, possibly over multiple lines