How to Operate MongoDB binary data with PHP
<?php
//PHP MongoDB operation, which is used to store binary data into a database
$connection = new MongoClient( "mongodb://127.0.0.1:27017" ); // Link to the remote server, using a custom port
$db = $connection->wenestthumb; //Create or Select Database
// select a collection:
$collection = $db->foobar;
//Insert binary data into the database
$data=file_get_contents("images/photo.jpg");
$profile = array(
"username" => "foobity",
"pic" => new MongoBinData($data, MongoBinData::GENERIC),
);
$collection->save($profile);
//Get a single record
$document = $collection->findOne();
//var_dump( $document['pic']->bin );
//header('Content-Type: image/jpg');
//exit($document['pic']->bin);//Output the picture
echo $collection->count().' ge ';//The number of statistical results
//Cycle through all results
$cursor = $collection->find();
foreach ( $cursor as $id => $value )
{
//echo "$id: ";
// var_dump( $value );
}
//Query by criteria
$query = array( 'username' => 'foobity' );
$cursor = $collection->find( $query );
//$collection->remove( $query );//Delete by condition
while ( $cursor->hasNext() )
{
var_dump( $cursor->getNext() );
}
//Create an index
//$collection->ensureIndex( array( "i" => 1 ) ); // create index on "i"
//$collection->ensureIndex( array( "i" => -1, "j" => 1 ) ); // index on "i" descending, "j" ascending
//Delete the collection
//$collection->drop();
//Close the connection
$connection->close();
?>
Leave a Reply