php 下使用mongo

php使用mongo笔记

下面是window下的php 的mongo扩展安装与使用

 

1. 需要先安装mongo,参考http://xiaoyu-91.iteye.com/blog/2338063

 

2. 我的php版本为5.3.10版本,下载5.3.10的扩展地址:

http://www.veryhuo.com/down/html/33980.html



 

如果是其他版本下载地址为:windows.php.net/downloads/pecl/releases/mongo

 

下载之后放在php的扩展文件夹中ext

 

3. 添加配置:

php.ini中添加 extension=php_mongo.dll

 

重启服务,然后就可以了。


4. php的使用

 1) 链接mongo

<?php
$connection = new Mongo(mongodb://192.168.0.108:27017); //连接到192.168.0.108:27017//27017端口是默认的。
$connection = new Mongo( "example.com" ); //链接到远程主机(默认端口)
$connection = new Mongo( "example.com:65432" ); //链接到远程主机的自定义的端口
print_r($connection->listDBs());//能打印出数据库数组,看看有几个数据库。

 

例:

index.php

<?php
       $mongo = new Mongo(); //或指定地址$mongo = new Mongo( "127.0.0.1:27017" );
        $db = $mongo->test;  // 选择数据库test
        $collection = $db->col;  // 选择person集合
        $data = array('name'=>'34','id'=>1);
//       $collection->insert($data);
                
          $obj = $collection->findOne();   // 查询集合里面一条文档
          var_dump( $obj );

 

输出结果:

array
  '_id' => 
    object(MongoId)[8]
      public '$id' => string '582d569d24d874ec0f000000' (length=24)
  'name' => string '34' (length=2)
  'id' => int 1

 

 2)插入数据:save,insert

 

 3)修改数据 : update

 

$newdata = array('$set' => array("title" => "Calvin and Hobbes"));
$collection->update(array("author" => "caleng"), $newdata);

 

 4)查询数据:find(),findOne(),

 

$res = $collection->find(); 
       foreach ($res as $id => $value) {
                    echo "$id: ";
                    var_dump( $value );
        }

 输出结果:

582d569d24d874ec0f000000:

array
  '_id' => 
    object(MongoId)[10]
      public '$id' => string '582d569d24d874ec0f000000' (length=24)
  'name' => string 'test213' (length=7)
  'id' => int 2

582d580f24d874ec0f000001:

array
  '_id' => 
    object(MongoId)[11]
      public '$id' => string '582d580f24d874ec0f000001' (length=24)
  'name' => string '34' (length=2)
  'id' => int 1

 

 5)统计总数:count()

 

//删除
$collection->remove(array('author'=>'caleng'), array("justOne" => true));

 

 

// 关闭链接
$m->close();

 

 


 

 

 http://www.runoob.com/mongodb/mongodb-insert.html

 

猜你喜欢

转载自xiaoyu-91.iteye.com/blog/2338587