MongoDB & PHP CRUD

摘要:MongoDB & PHP CRUD

登入取得collection

    $conn= new Mongo("mongodb://user:password@localhost:27017");
    $db = $conn->selectDB('inbox_server');
    $db->authenticate("user","password");
    $collection = new MongoCollection($db,'inboxs');

Select

    echo "mongo.find()"."
";
    $query_doc = array();
    $cursor = $collection->find($query_doc);
    echo "total count ".$cursor->count()."
";
    $count = 0 ;
    foreach ($cursor as $doc) {
        //var_dump($doc);
    	echo $doc["_id"]."
";
    	foreach($doc["data"] as $data) 
    	{
    	    echo $data["timestemp"].":";
            var_dump($data);
    		echo "
";
    		
    	}	
    	echo $doc["update_time"]."
";
        $count++;
        if($count===5)
        {
            break;
        }
    }

insert 

    echo "mongo.insert()"."
";
    $data = array(
	    'data'=>array(
	        array('timestamp'=>time()),
	    'update_time'=>time()
	);
	
	$collection->insert($data);
    
    echo 'inserted document with ID:'.$data['_id'];

Update

    echo "mongo.update()"."
";
    $data = $collection->findOne();
	$data["data"][0]["timestamp"]=time();
	$collection->save($data);

Delete

";
    $data = $collection->findOne();
	$collection->remove($data);
    $conn->close();
} catch (MongoConnectionException $e){
    die('Error conne cting to MongoDB server');
} catch (MongoException $e){
    die('Error:' . $e->getMessage());
}

?>