`
lobbychmd
  • 浏览: 8878 次
  • 性别: Icon_minigender_1
  • 来自: 广州
最近访客 更多访客>>
文章分类
社区版块
存档分类

mongoDB in action (2)

阅读更多

Getting and Starting MongoDB

MongoDB 几乎是作为网络服务运行,客户端可以进行访问和操作,要启动mongodb,运行mongod可执行文件

$ ./mongod

./mongod --help for help and startup options

Sun Mar 28 12:31:20 Mongo DB : starting : pid = 44978 port = 27017 dbpath = /data/db/ master = 0 slave = 0  64-bit

Sun Mar 28 12:31:20 db version v1.5.0-pre-, pdfile version 4.5

Sun Mar 28 12:31:20 git version: ... Sun Mar 28 12:31:20 sys info: ...

Sun Mar 28 12:31:20 waiting for connections on port 27017

Sun Mar 28 12:31:20 web admin interface listening on port 28017

 

Or if you’re on Windows,  run this:

$ mongod.exe

 

  

 

 

如果没有参数,mongod 将用缺省的数据目录 /data/db/ ( win C:\data\db\), 端口27017. 如果目录不存在或者没有权限服务将运行失败. 端口被占用也会失败,通常是因为已经运行了另外一个mongodb 的实例.

 

服务将显示一些版本和系统信息,然后等待连接。Mongod 还将启动一个http服务(端口是主端口+1000 这里就是28017.了。这样你可以用浏览器获取一些信息

Ctrl-c 可以终止服务

 

 

 

 
 

MongoDB Shell

MongoDB 自带一个交互式的js控制台允许在命令行来。对于管理功能、检查实例来说很有用。或者只是玩玩. Mongodb shell 是有用的工具,在余下的文字中会经常用到。

 

Running the Shell

To start the shell, run the mongo executable:

$ ./mongo

MongoDB shell version: 1.6.0 url: test

connecting to: test type "help" for help

> 

 

运行就尝试连接服务了,所以要先启动服务。

 

这个shell 是完全的js 语法, 具备运行任意的js 能力. 为了说明这个,我们输入一个简单的数学公式

> x = 200

200

> x / 5;

40

 

也可以调用所有标准的js

> Math.sin(Math.PI / 2);

1

> new Date("2010/1/1");

"Fri Jan 01 2010 00:00:00 GMT-0500 (EST)"

> "Hello, World!".replace("World", "MongoDB"); Hello, MongoDB!

 

也可以定义js 函数

> function factorial (n) {

... if (n <= 1) return 1;

... return n * factorial(n - 1);

... }

> factorial(5);

120

 

注意你可以创建一个多行的命令。当你按回车的时候Shell 会检测什么时候js 语句完成了如果没有的话会等待你按下一行


A MongoDB Client

虽然执行完成js 的能力很酷,shell 的真正威力是在于它其实是一个单独的mongodb客户端。一开始,shell 连接test数据库并将链接赋值给全局变量db。这个变量是shell链接服务的主要进入点。

Shell包含一些插件, The shell contains  some add-ons that are not valid JavaScript syntax but were implemented because of their familiarity to users of SQL shells. 这些插件不会提供任何更深入的功能。但它们是 很好的语法糖。例如一个最重要的选择数据库的命令:

> use foobar

switched to db foobar

这个时候如果你查看db变量就会变成了

 

> db foobar

 

因为这是一个js shell,一个变量输入回车将被打印出来

Db变量可以访问集合。Db.baz 返回当前数据库的baz 集合。现在我们可以在shell 中存储集合,我们可以执行几乎所有的数据操作。

 

Basic Operations with the Shell

我们可以用4个基本的操作: create,  read, update,  and  delete (CRUD),  shell 里面操作和查看数据。

 

 

Create

Insert 函数吧一个文档加入集合,例如假设我们要存储一个博客文章,首先我们创建一个本地变量叫post,是一个js object,表示一个文档,它有title 而后content 2key。和日期

> post = {"title" : "My Blog Post",

... "content" : "Here's my blog post.",

... "date" : new Date()}

{

"title" : "My Blog Post",

"content" : "Here's my blog post.",

"date" : "Sat Dec 12 2009 11:23:21 GMT-0500 (EST)"

}

 

这个对象是一个合法的mongodb 文档。所以我们可以将它插入blog集合


> db.blog.insert(post)

这个博客温江已经存入数据库。我们可以用find来找到它

> db.blog.find()

{

"_id" : ObjectId("4b23c3ca7525f35f94b60a2d"), "title" : "My Blog Post",

"content" : "Here's my blog post.",

"date" : "Sat Dec 12 2009 11:23:21 GMT-0500 (EST)"

}

你可以看到产生了一个_id 的键值对。

 

Read

Find返回集合的所有文档。如果我们只是找一个文档,就用findone:

> db.blog.findOne()

{

"_id" : ObjectId("4b23c3ca7525f35f94b60a2d"), "title" : "My Blog Post",

"content" : "Here's my blog post.",

"date" : "Sat Dec 12 2009 11:23:21 GMT-0500 (EST)"

}

 

find and findOne can also be passed criteria in the form of a query document. 它将限制一个查询的匹配. Shell自动显示每个find 20document,但可以fetch 更多

 

Update

如果我们要修改一个文章,用uodate。最少2个参数,第一个是如何找到要update 的准则,第二个是新文档。设想我们决定允许早前发布的一个文章可以评论,我们需要增加一个key并设置值为评论的数组

首先修改post 变量,增加comments :

 

> post.comments = [] [  ]

 

然后执行update,将tigle “My Blog Post” 替换为新版本的文档

> db.blog.update({title : "My Blog Post"}, post)


限制文档有了一个"comments" . 如果重新find 一下就会看到新key

> db.blog.find()

{

"_id" : ObjectId("4b23c3ca7525f35f94b60a2d"), "title" : "My Blog Post",

"content" : "Here's my blog post.",

"date" : "Sat Dec 12 2009 11:23:21 GMT-0500 (EST)" "comments" : [ ]

}

 

Delete

remove 将文档从数据库永久删除。没有参数就删除集合的所有文档. 也可以指定一个文档来删除,例如删除刚才键入的文档

> db.blog.remove({title : "My Blog Post"})

 

Now the collection will be empty again.

 

Tips for Using the Shell

因为mongo 只不过是一个js shell, 你可以阅读js 在线文档获得帮助. Shell也内置了help命令:

> help

HELP

show dbs                  show database names

show collections          show collections in current database show users   show users in current database

show profile              show recent system.profile entries w. time >= 1ms use <db name> set current database to <db name>

db.help()                 help on DB methods db.foo.help()    help on collection methods 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

 

db.help()提供了数据库层次的help;, 在集合的层次是这样 db.foo.help();.

 

一个很好的方法可以描述一个函数是如何工作的,就是不要敲入括号. 将显示源代码. 例如, 如果我们好奇update 是如何工作的,或者不记得参数顺序了,可以这样

> db.foo.update

function (query, obj, upsert, multi) { assert(query, "need a query"); assert(obj, "need an object"); this._validateObject(obj);

this._mongo.update(this._fullName, query, obj,


upsert ? true : false, multi ? true : false);

}

 

There is also an autogenerated API of all the JavaScript functions provided by the shell at http://api.mongodb.org/js.

 

Inconvenient collection names

 

db.collectionName 一般都正常运行,除非这个collectionName 刚好是一个类属性.例如假设想访问 version 集合,就不能用db.version 因为它是一个函数(返回正在运行的mongodb 的版本).

> db.version function () {

return this.serverBuildInfo().version;

}

 

db’s collection-returning behavior is only a fallback for when JavaScript cannot find a matching property.  如果有一个属性 是跟集合同名的,我们可以getCollection 函数:

> db.getCollection("version");

test.version

 

 这个方法还可以处理不合法的js变量名.例如foo-bar是一个合法的集合名,但它在js 厘米代表变量的减法,因此要访问foo-bar集合可以用 db.getCollection("foo-bar").

js 里面, x.y 代表 x[‘y’],这意味着可以用变量来访问子集合,而不仅仅是常量.如果我们要对每个blog 的子集合进行操作,可以用下面的方式:

var collections = ["posts", "comments", "authors"];

 

for (i in collections) {

doStuff(db.blog[collections[i]]);

}

 

来代替这几句:

 

doStuff(db.blog.posts); doStuff(db.blog.comments); doStuff(db.blog.authors);

0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics