PHP操作MongoDB学习

| |
2012/10/26 11:21 ArthurXF
1   mongodb启动时,设置启动项

C:\>mongodb\bin\mongod  --config C:\mongodb.conf
其中mongodb.conf为:
    dbpath = D:\mongodb_data    
   logpath  = D:\mongodb.log      
   logappend  = true
如果是linux的话,则mongod  --config /etc/mongodb.conf

2  停止server
    db.shutdownServer()

3  常用操作:
   use myfirstdb
  插入db
   db.movies.insert({name:"Source Code", genre:"sci-fi", year:2011})
   查找所有记录
   db.movies.find()

4  . PHP MongoDB 扩展安装
  php 5.2 mongo driver下载:
http://downloads.mongodb.org/mongo-latestphp5.2vc6ts. zip
  5.3 mongo driver下载:
  http://downloads.mongodb.org/mongo-latest-php5.3vc6ts.zip
   把DLL复制到extension目录,然后
extension=php_mongo.dll即可

5  列出当前数据库的php mongodb程序

<?php
try{
$mongo = new Mongo(); //create a connection to MongoDB
$databases = $mongo->listDBs(); //List all databases
echo '<pre>';
print_r($databases);
$mongo->close();
} catch(MongoConnectionException $e) {
//handle connection error
die($e->getMessage());
}
?>


如果是连接时用不同的端口,构造函数中用:
$mongo  = new Mongo($server="mongodb://localhost:8888");
也可以指定timeout的策略;

try {
$mongo = new Mongo($options=array('timeout'=> 100))
} catch(MongoConnectionException $e) {
die("Failed to connect to database ".$e->getMessage());
}


6  通过PHP保存对象到mongo db中

$connection = new Mongo();
$database   = $connection->selectDB('myblogsite');
$collection = $database->selectCollection('articles');
$article               = array();
$article['title']     = $_POST['title'];
$article['content']   = $_POST['content'];
$article['saved_at'] = new MongoDate();
           
$collection->insert($article);


注意的是,默认不用显式create  database即可,如果不存在则会自动
新建立database,也可以:

$connection = new Mongo();
$collection = $connection->myblogsite->articles;

// mongodb的插入是异步的,如果不想异步,可以这样;
try {
$status = $connection->insert(array('title' => 'Blog Title',
'content' => 'Blog Content'),
array('safe' => True));
echo "Insert operation complete";
} catch (MongoCursorException $e) {
die("Insert failed ".$e->getMessage());
}



  则必须等插入完成后才返回给用户,继续执行下一条语句
    也可以指定timeout的策略:
    $collection->insert($document, array('safe' => True,
'timeout'  => True));

7  设置自己的自增id
 
    $document = array('_id' => hash('sha1', $username.time()),
     将设置id为username后加上当前时间再hash.

8  日期设置

$article['saved_at'] = new MongoDate();
$timestamp = new MongoDate(strtotime('2011-05-21 12:00:00'));
print date('g:i a, F j', $timestamp->sec); //prints 12 pm, May 21


$lastweek = new MongoDate(strtotime('-1 week')); //找出一个星期以来的记录
$cursor = $articleCollection->find(array('saved_at' =>
array('$gt' => $lastweek)));


指定一定范围内的记录:

$start = new MongoDate(strtotime('2011-05-01 00:00:00'));
$end = new MongoDate(strtotime('2011-05-31 23:59:59'));
$articleCollection->find(array('saved_at'=>
array('$gte' => $start,
'$lte' => $end)));


9  列出某个表的所有记录

$cursor = $collection->find();
<?php while ($cursor->hasNext()):
$article = $cursor->getNext(); ?>
<h2><?php echo $article['title']; ?></h2>


找某条记录:$article  = $collection->findOne(array('_id'=>
new  MongoId($id)));
查找时也可以传入多个参数:
$moviesCollection->find(array('genre'  => 'comedy', 'year' => 2011));
if  ($cursor->count() === 0)  //如果找不到
   如果查询多个条件:
   $collection->find(array('x' => array('$gt' => 100)));
  //$ is escaped within double quotes (")
  $collection->find(array('x' => array("\$gt" => 100)));
   注意要用单引号,如果要用双引号,则要加上转义符。

10  排序:
     $cursor->sort(array('saved_at' => -1)) //按save_at字段降序排列,1为升序

11  skip和limit:
     

$cursor = $articleCollection->find();
//skip the first five articles in the cursor
$cursor->skip(5);
$cursor->limit(10);//结果集只取10条


12  更新数据库
   $articleCollection->update(array('_id' => new MongoId($id)), $article);
   第一个参数为指定的条件(更新条件),第二个参数为要更新的对象
还有可选参数如下;
   $collection->update($criteria, $newobj, array('safe' => True));
   safe=true时,等到UPDATE结束才返回结果
  mongodb还支持upsert的操作:如果存在则更新,如果不存在则插入
    $users->update(array('email' => 'alice@wonderland.com'),
array('firstname'  => 'Alice', 'lastname'=> 'Liddell'),
array('upsert'  => True));

     这里对email为alice@wonderland.com的记录进行更新其firstname,lastname字段的内容

13  修饰符
     比如set,只修改记录的某个部分,可以这样:

$articles->update(array('_id' => MongoId('4dcd2abe5981')), array('$set' => array('title' => 'New Title')));

   使用inc:

$articles->update(array('_id' => MongoId('4dcd2abe5981')), array('$set' => array('content' => 'New Content'),
'$inc' => array('update_count' => 1))

);
// 将update_count+1

   unset:

$articles->update(array('_id' => MongoId('4dcd2abe5981')), array('$unset' => array('title' => True)));
// 将title field从这个document中移除

  更名rename:

$articles->update(array(),
array('$rename' => array('saved_at' => 'created_at')),
array('multiple' => True)

);
//  将save_at更名为create_at

 
14  删除记录

$articleCollection->remove(array('_id' => new MongoId($id)));
$movies->remove(array('genre' =>'drama'), array('justOne' => True));

  如果加了justOne的参数,则只删除符合条件的一条记录而已,其他不删除

15  document的关系

1)嵌套

 {
  "_id" : ObjectId("4dd491695072aefc456c9aca"),
  "username" : "alphareplicant",
  "email" : "roybatty@androids.org",
  "fullname" : "Roy Batty",
  "joined_at" : ISODate("2011-05-19T03:41:29.703Z"),
"address" : {
    "street" : "13 Tannhauser Gate",
    "city" : "Caprica",
    "state" : "CC",
    "zipcode" : 512
},
}



  2)引用

{
_id : ObjectId("4dcd2abe5981aec801010000"),
title : "The only perfect site is hind-site",
content : "Loren ipsum dolor sit amet…",
saved_at : ISODate('2011-05-16T18:42:57.949Z'),
author_id : ObjectId("4dd491695072aefc456c9aca")
}


3)比如一个一对多的关系:
  比如一个文章下的评论:

$comment = array(
'name' => $_POST['commenter_name'],
'email' => $_POST['commenter_email'],
'comment' => $_POST['comment'],
'posted_at' => new MongoDate()
);
$collection->update(array('_id' => new MongoId($id)), array('$push' => array('comments' => $comments)));  


使用的是$push的修饰符,一般来说,用内嵌的document效率比较高
或者:

$article = $articleCollection->findOne(array('_id' => new MongoId($id)));
$comments = (isset($article['comments'])) ? $article['comments'] : array();
$comment = array(
                   'name' => $_POST['commenter_name'],
                   'email' => $_POST['commenter_email'],
                   'comment' => $_POST['comment'],
                   'posted_at' => new MongoDate()
               );
               
array_push($comments, $comment);
$articleCollection->update(array('_id' => new MongoId($id)), array('$set' => array('comments' => $comments)));


  使用.号来查询子嵌套文档

{
  name : "Gordon Freeman",
address : {
   city : "Springfield",
   state : "Florida"
}
}
{
name : "Lara Croft",
address : {
   city : "Miami",
  state: "Florida"
}
}
// 则查询address中state为florida的document:


$users->find(array('address.city' => 'Springfield', 'address.state' => 'Florida'));

Tags:
Mongodb | 评论(0) | 引用(0) | 阅读(5058)
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   游客无需密码
网址   电邮   [注册]