本文主要总结一下在使用 Meteor 开发过程中对 mongodb 数据库的管理。其中包含使用命令行终端(meteor shell)进行管理,还有图形化界面的工具 Robomongo 工具。

预备知识

当使用 meteor 命令启动 meteor 项目后,meteor 会默认使用 3000 端口作为 web 项目的端口,我们可以通过 http://domainName:3000/ 这样的地址来访问我们的网站。而数据库所使用的端口,则是在这个端口基础上 +1,就是 3001 端口。也就是说,如果你指定启动 meteor 项目时使用了其他端口,比如 meteor -p 8000,那么 mongodb 的数据库连接端口就是 8001

使用 meteor shell 进行管理

通过 meteor shell 管理 mongodb 不需要指定端口,你只要在 meteor 项目启动后的项目目录下执行 meteor mongo 就可以连接到数据库了。如下:

1
2
3
4
myCode:~/Project/microduino$ meteor mongo
MongoDB shell version: 2.6.7
connecting to: 127.0.0.1:3001/meteor
meteor:PRIMARY>

这样就连接到了当前项目的 mongodb 数据库,通过 help 命令可以看到帮助。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
meteor:PRIMARY> help
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

通过 show dbs 命令可以查看当前的数据库列表。

1
2
3
4
meteor:PRIMARY> show dbs
admin (empty)
local 0.063GB
meteor 0.031GB

上面我们看到,有一个名为 meteor 占用 0.031GB 的空间,使用命令 use meteor 选择它,然后使用命令 show collections 查看所有数据库。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
meteor:PRIMARY> use meteor
switched to db meteor
meteor:PRIMARY> show collections
Accounts
AnalyticsEvents
Articles
Cards
Cart
Discounts
Orders
Packages
Products
Sessions
Shipping
Shops
Tags
Taxes
Translations
cfs.Images.filerecord
cfs._tempstore.chunks
cfs_gridfs._tempstore.chunks
cfs_gridfs._tempstore.files
friends
meteor_accounts_loginServiceConfiguration
meteor_oauth_pendingCredentials
meteor_oauth_pendingRequestTokens
modules
oldUsers
roles
system.indexes
users

如果要对数据库进行查询,那么此时你就可以使用命令 db.collectionName.find(...); 来操作了。下面我们来介绍图形化界面的 Robomongo。

使用 Robomongo 管理数据库

下载地址:http://robomongo.org/ 安装完成后,配置连接属性,程序刚打开的时候一片空白,我们要手动点右键 Add 一个新的连接。 屏幕快照 2015-12-28 16.09.31 输入 mongodb 的连接信息,记住这个端口,要根据你项目启动的端口来决定的。 屏幕快照 2015-12-28 16.09.59 保存后点击 Connect 连接 屏幕快照 2015-12-28 16.10.24 连接上以后,就可以通过 meteor->Collections 看到所有的数据库信息了 屏幕快照 2015-12-28 16.10.51 如果想执行查询、更新等语句,可以双击一个数据库,再右侧数据列表的上方输入查询语句 屏幕快照 2015-12-28 16.55.09