本博文介绍了MongoDB,并详细指引读者在Ubuntu下MongoDB的安装和使用。本教程在Ubuntu14.04下测试通过.(2017.09.07)
安装MongoDB
MongoDB安装很简单,无需下载源文件,可以直接用apt-get命令进行安装。
打开终端,输入以下命令:
sudo apt-get install mongodb
安装完成后,在终端输入以下命令查看MongoDB版本:
mongo -version
输出版本信息,表明安装成功,如下:
root@ubantu:/usr/src# mongo -version
MongoDB shell version: 2.4.9
启动和关闭mongodb命令如下:
service mongodb start
输入命令,结果如下:
root@ubantu:/usr/src# service mongodb start
start: Job is already running: mongodb
service mongodb stop
默认设置MongoDB是随Ubuntu启动自动启动的。
输入以下命令查看是否启动成功:
pgrep mongo -l #注意:-l是英文字母l,不是阿拉伯数字1
卸载MongoDB
sudo apt-get --purge remove mongodb mongodb-clients mongodb-server
使用MongoDB
shell命令模式
输入mongo
进入shell命令模式,默认连接的数据库是test数据库,在此之前一定要确保你已经启动了MongoDB,否则会出现错误,启动之后运行成功,如下图:
root@ubantu:/usr/src# mongo
MongoDB shell version: 2.4.9
connecting to: test
Welcome to the MongoDB shell.
For interactive help, type “help”.
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user
>
常用操作命令:
db.help() help on db methods
db.mycoll.help() help on collection methods
sh.help() sharding helpers
rs.help() replica set helpers
help admin administrative help
help connect connecting to a db help
help keys key shortcuts
help misc misc things to know
help mr mapreduce
show dbs show database names
show collections show collections in current database
show users show users in current database
show profile show most recent system.profile entries with time >= 1ms
show logs show the accessible logger names
show log [name] prints out the last segment of log in memory, ‘global’ is default
use <db_name> set current database
db.foo.find() list objects in collection foo
db.foo.find( { a : 1 } ) list objects in foo where a == 1
it result of the last line evaluated; use to further iterate
DBQuery.shellBatchSize = x set default number of items to display on shell
exit quit the mongo shell