整理来自
https://www.shiyanlou.com/courses/running/57
启动
$ sudo service mongodb start
进入MongoDB命令行操作界面,在命令行中敲exit可以退出
$ mongo
实验中的布尔类型的ture用1代替,false用0代替
范例:进入mongoDB命令行操作界面之后,进行如下操作:
> use Chenshi switched to db Chenshi
您可以使用db命令查看您当前选择的数据库
> db Chenshi
您也可以通过使用show dbs命令查看所有的数据库
> show dbs
在这条命令之后您刚才创建的Chenshi不会显示,这只有在您像数据库中插入了数据之后才能显示
假设刚才我们使用语句db.computer.insert({"name":"shiyanlou"})对数据库Chenshi进行了数据插入操作
> show dbs #显示当前系统中的所有数据库 > use Chenshi #转到Chenshi数据库 switched to db Chenshi > db.dropDatabase() {"dropped":"Chenshi","ok":1} > show dbs
语法:
db.createCollection(name,options)
参数描述:
范例:
> db.createCollection("shiyanlou") #无参数 { "ok" : 1 } > show collections shiyanlou system.indexes > db.createCollection("shiyanlou2", { capped : 1, autoIndexID : 1, size : 6142800, max : 10000 } ) #带参数 { "ok ": 1 }
参数描述:
操作实例:
> use Chenshi switched to db Chenshi > show collections shiyanlou shiyanlou2 system.indexes > db.shiyanlou.drop() ture > show collections shiyanlou2 system.indexes
删除成功
注意:当您要删除指定的集合时,用您想要删除的集合名称替代COLLECTION即可
操作实例:
> userdoc1=({"user_id":1,"name":"cloud","state":"active","actor":"user","e-mail":" test@qq.com","VM_num":2,"time":[{"date":"2014-08-12","hour":"10:53 PM"}] }) > userdoc2=({"user_id":2,"name":"testadmin","state":"active","actor":"admin","e-mail":" test@qq.com","VM_num":2,"time":[{"date":"2014-08-11","hour":"06:34 AM"}] }) > doc1=({"name":"peter","position":"teacher"}) #先定义文档 > use Chenshi switched to db Chenshi > db.shiyanlou.insert(userdoc1) WriteResult({"nInserted":1}) > db.shiyanlou.insert(userdoc2) WriteResult({"nInserted":1}) > db.shiyanlou.insert(doc1) WriteResult({"nInserted":1})
插入文档成功,当然也可以直接将文档的内容作为函数的参数直接替代document
操作实例:
> db.shiyanlou.update({"user_id":"02","e-mail":"test@qq.com"},{$set:{"e-mail":"group@qq.com"}}) WriteResult({"nMatched":1,"nUpserted":1,"nModified":1}) > db.shiyanlou.find()
操作实例:
db.shiyanlou.update({"e-mail":"test@qq.com"},{$set:{"e-mail":"group@qq.com"}},{multi:ture})
操作实例:
> db.shiyanlou.save({"_id":ObjectId("53ea174ccb4c62646d9544f4"),"name":"Bob","position":"techer"}) WriteResult({"nMatched":1,"nUpserted":1,"nModified":1})
跟update差不多,但是update更好用
操作实例:
> db.shiyanlou.remove({"name":"Bob"}) WriteResult({"nRemoved":1})
其实remove函数的参数跟update函数的第一个参数一样,相当于查找条件,注意,不要误删!
删除后可以用查找命令确认数据:
> db.shiyanlou.find()