php操作mongodb

2510 ワード

<?php
//     http://www.cnblogs.com/huangxincheng/archive/2012/02/18/2356595.html

//              
$conn = new MongoClient("mongodb://127.0.0.1:27017/");
//     
$db = $conn->cx;
//     ,    
$collection = $db->log;

$do=$_GET['do'];

//       
if($do=='dblist'){
    var_dump($conn->listDBs());
}



//    
if($do=='insert'){

    $doc = array(
        "name" => "33222",
        "type" => "database",
        "count" => 1,
        "versions" => array('0.9.7', '0.9.8', '0.9.9')
    );
    $collection->insert($doc);//    
}

//      
if($do=="selectone"){
    $obj = $collection->findOne();//     
    print_r($obj);

    $obj = $collection->findOne(array("name"=>"ddd"));//      
    print_r($obj);
}

if($do=="selectall"){
    $cursor = $collection->find();
    $cursor = $collection->find(array("count"=>array('$gt'=>1,'$lte'=>74)))->limit(2)->fields(array("type"=>true,"name"=>true));
    //->sort(array(‘age’=>-1,’type’=>1)); ##1     -1    ,           
    foreach ($cursor as $id => $value) {
        echo "$id: ";
        print_r( $value );
    }
}

//    
if($do=="count"){
    echo $collection->count();
    echo $collection->count(array("name"=>"ddd"));
}


//  
if($do=="update"){
    $where=array('count'=>3);
    $newdata=array('type'=>'www2','count'=>43);
    $result=$collection->update($where,array('$set'=>$newdata),array('multiple'=>true)); #$set:         ,     $pull $pullAll $pop $inc,         
}
//  
if($do=="replace"){
    $where=array('name'=>'qqq');
    $newdata=array('type'=>'234','count'=>3);
    $result=$collection->update($where,$newdata);
}
//  
if($do=='remove'){
    $where=array('count'=>134);
    $collection->remove($where);
}