<?php
//php mongodb 操作,用于把 二进制数据存入数据库
$connection = new MongoClient( "mongodb://127.0.0.1:27017" ); // 链接到远程服务器,使用自定义的端口
$db = $connection->wenestthumb; //创建 or 选择数据库
// select a collection:
$collection = $db->foobar;

//把二进制数据插入数据库
$data=file_get_contents("images/photo.jpg");
$profile = array(
"username" => "foobity",
"pic" => new MongoBinData($data, MongoBinData::GENERIC),
);

$collection->save($profile);

//获取单条记录
$document = $collection->findOne();
//var_dump( $document['pic']->bin );
//header('Content-Type: image/jpg');
//exit($document['pic']->bin);//输出图片
echo $collection->count().' ge ';//统计结果数量

//循环显示所有结果
$cursor = $collection->find();
foreach ( $cursor as $id => $value )
{
//echo "$id: ";
// var_dump( $value );
}
//按条件查询
$query = array( 'username' => 'foobity' );
$cursor = $collection->find( $query );
//$collection->remove( $query );//按条件删除
while ( $cursor->hasNext() )
{
var_dump( $cursor->getNext() );
}

//创建索引
//$collection->ensureIndex( array( "i" => 1 ) ); // create index on "i"
//$collection->ensureIndex( array( "i" => -1, "j" => 1 ) ); // index on "i" descending, "j" ascending
//删除集合
//$collection->drop();
//关闭连接
$connection->close();

来源 http://blog.p2hp.com/archives/1927
?>

用php操作mongodb
标签: