日期:2014-05-16  浏览次数:20485 次

mongodb实践 1

项目上用过Memcached,最近学习了一下mongodb。把学习过程总结一下:

注册iteye三年了,这是头一回发文章,实在惭愧:(

?

?

mongodb是一个开源的文档型数据库,是一种典型的NoSql数据库。mongodb官网上介绍mongodb的用例包括:实时分析、日志处理、电子商务、文档归档等。

一下内容是本人学习mongodb时的笔记,主要是shell操作的部分。

?

#mongodb安装

?

*下载mongodb的安装文件mongodb-win32-x86_64-1.6.5.zip,将其解压,为了方便将解压后的文件名命名为mongodb,如:F:/mongodb。

*创建mongodb的数据库存储文件夹,如F:/data/db。

*进入cmd,cd到~/bin目录,输入mongod -dbpath=F:/data/db(经测试"/"和"\"均能都可以使用--注:window7环境,"~"代表安装目录)启动mongodb数据库,可按Ctrl+C关闭数据库。

*再打开cmd窗口,cd到~/bin,输入mongo命令,默认连接到test数据库,输入db命令可查看所有数据库。

?

此时F:/data/db目录下空空如也,因为mongodb并没有正在创建test数据库,当有数据插入操作是mongodb才会真正创建数据库,同理使用use命令切换到某个本来不存在数据库下并不代表数据库

被真正创建了。

mongodb的官网上这么说@

给有其他数据库经验的开发者的提示

在下面的例子中你可能会注意到,我们没有创建数据库和聚集。MongoDB并不用那么做。一旦你插入数据,MongoDB会建立对应的聚集和数据库。要是查询了不存在的聚集,Mongo就将其视为空的聚集。

使用 use 命令来切换数据库不会立即创建数据库 - 数据库会在首次插入数据时延迟创建。这意味着如果首次 use 一个数据库,该数据库不会在 show dbs 命令的列表里显示出来,直到插入数据。

?

#连接到数据库,通过shell来操作数据库

?

#连接数据库,获取帮助信息

?

*~/bin/mongo.exe文件是shell命令的执行文件(注:此shell非彼shell,不要与Unix下的shell混淆),这里的shell实际上就是js。打开一个cmd窗口,cd到~/bin,输入mongo -h命令,得到如下帮助信息@

?

	MongoDB shell version: 1.6.5
	usage: mongo [options] [db address] [file names (ending in .js)]
	db address can be:
	  foo                   foo database on local machine
	  192.169.0.5/foo       foo database on 192.168.0.5 machine
	  192.169.0.5:9999/foo  foo database on 192.168.0.5 machine on port 9999
	options:
	  --shell               run the shell after executing files
	  --nodb                don't connect to mongod on startup - no 'db address' 
				arg expected
	  --quiet               be less chatty
	  --port arg            port to connect to
	  --host arg            server to connect to
	  --eval arg            evaluate javascript
	  -u [ --username ] arg username for authentication
	  -p [ --password ] arg password for authentication
	  -h [ --help ]         show this usage information
	  --version             show version information
	  --ipv6                enable IPv6 support (disabled by default)
?

?

?

file names: a list of files to run. files have to end in .js and will exit after unless --shell is specified

#向数据库插入数据

?

*在shell中输入命令@

?

> r = {name:"mongo"};

		{ "name" : "mongo" }
		> db.things.save(r);
		> r = {description : "mongodb is a no sql db"}
		{ "description" : "mongodb is a no sql db" }
		> db.things.save(r);
		> db.things.find();
		{ "_id" : ObjectId("4ee84d530c16000000006ec4"), "name" : "mongo" }
		{ "_id" : ObjectId("4ee84dee0c16000000006ec5"), "description" : "mongodb is a no sql db" }
?

?

mongodb是自由模式,或者说是动态模式的,mongodb的官网上如是说@

?

写道

A MongoDB collection is a collection of