发布于 2015-06-22 03:50:32 | 242 次阅读 | 评论: 0 | 来源: 网络整理

想要在 PHP 中使用MongoDB,需要使用 MongoDB 的 PHP驱动程序。从URL下载PHP驱动程序。请一定要下载它的最新版本。现在,解压存档并把php_mongo.dll,放在 PHP 扩展目录(默认情况下为“ext”),并添加下面一行到php.ini文件: 


extension=php_mongo.dll

建立连接,并选择一个数据库

要连接,需要指定数据库名称,如果数据库不存在,则 MongoDB 会自动创建它。

代码片段连接到数据库,如下:


<?php
   // connect to mongodb
   $m = new MongoClient();

   // select a database
   $db = $m->mydb;
?>

获取/选择一个集合

代码片段/选择一个集合:


<?php
   $collection = $db->mycol;
?>

插入文档

将文档插入到 MongoDB ,使用insert() 方法。

代码片段插入文档:


<?php
   $document = array( 
      "title" => "MongoDB", 
      "description" => "database", 
      "likes" => 100,
      "url" => "#/",
      "by", "phperz.com"
   );
   $collection->insert($document);
?>

查找从集合中的所有文档

要选择从集合中所有文档,使用find()方法。

选择所有文档的代码片段:


<?php
   $cursor = $collection->find();

   // iterate cursor to display title of documents
   foreach ($cursor as $document) {
      echo $document["title"] . "n";
   }
?>

其余的 MongoDB 方法 findOne(), save(), update(), limit(), skip(), sort() 等工作原理在随后的教程说明。

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务