PHP with MongoDB

MongoDB的特点

MongoDB是一个可扩展的,高性能,开源,模式自由,面向文档的数据库.使用C++编写,MongoDB特点:

  • 面向文档存储(类JSON数据模式简单而强大)
  • 动态查询
  • 全索引支持,扩展到内部对象和内嵌数组
  • 查询记录分析
  • 快速,就地更新
  • 高效存储二进制大对象 (比如照片和视频)
  • 复制和故障切换支持
  • MapReduce 支持复杂聚合
  • 商业支持,培训和咨询

MongoDB 在键值存储(快速并有高扩展性) 和传统 RDBMS 系统(提供结构化模式和强大的查询)之间建立了一个桥梁.

MongoDB 安装

MongoDB 的官网提供了MAC OS 的二进制下载,解压即可使用,非常方便。用户无需在自己安装,由于32位的MongoDB 仅仅能够支持2G的存储,因此运营环境还是要使用64位的

1: 安装MonoDB

curl -O http://fastdl.mongodb.org/osx/mongodb-osx-i386-1.5.4.tgz

sudo tar mongodb-osx-i386-1.5.4.tgz

sudo mv mongodb-osx-i386-1.5.4 mongodb

2:安装PHP扩展

sudo pecl install mongo //使用PECL 安装扩展

sudo vi /usr/local/php/etc/php.ini // 修改php.ini文件

增加extension = “mongo.so”

启动MongoDB

创建数据文件存放的目录

mkdir -cp /data/db

/usr/local/mongodb/bin/mongod –dbpath=/data/db

PHP MongoDB 使用实例

<?php

$mongo = new Mongo(’localhost:27017′);

$db = $mongo->mydb;  // 选择一个数据库,如果没有则MongoDB会自动创建

$collection = $db->pblog; // 选择一个集合,如果没有则MongoDB会自动创建

$doc = array(”name” => “MongoDB”,

“type”   => “database”,

“count” => 1,

“info” => (object)array( “x” => 203,

“y” => 102),

“versions”  => array(”0.9.7″, “0.9.8″, “0.9.9″)

);

//$collection->insert( $doc );

for($i=0; $i < 100; $i++ ){

$collection->insert( array( “$i” => $i));

}

echo $collection->count();

$query = array( “71″ => 71);

$cursor = $collection->find($query);

while($cursor->hasNext()){

var_dump($cursor->getNext());

}

/*

$cursor = $collection->find();

foreach ($cursor as $id => $value){

echo “$id: “;

var_dump( $value );

}

*/

$obj = $collection->findOne();

var_dump($obj);

相关日志

3 Responses to “PHP with MongoDB”

  1. QQ农场 Says:

    博主是牜淫,太高深了。

    [回复]

    Abuer Reply:

    @QQ农场, 呵呵,足够的简单

    [回复]

  2. Plumbers in Darlington Says:

    Just had to enable you to be aware of the fact that I will likely not ever truly agree with the things you had to point out yet I have the ability to notice where you are coming from.

    [回复]

Leave a Reply