时间:2021-07-01 10:21:17 帮助过:47人阅读
sudo pecl install mongo
vim /srv/php/etc/conf.d/mongo.ini extension=mongo.so
<?php
$connection = new MongoClient( "mongodb://neo:chen@192.168.6.1" );
$db = $connection->test;
$grid = $db->getGridFS();
$id = $grid->put("/etc/passwd");
<?php
$connection = new MongoClient( "mongodb://neo:chen@192.168.6.1" );
$db = $connection->test;
$grid = $db->getGridFS();
$id = $grid->put("/etc/passwd");
$oid = new MongoId($id);
$file = $grid->get($oid);
echo $file->getBytes();
storeFile 与 put 类似
<?php
$connection = new MongoClient( "mongodb://neo:chen@192.168.6.1" );
$db = $connection->test;
$grid = $db->getGridFS();
$storedfile = $grid->storeFile("/etc/passwd", array("date" => new MongoDate()));
// Return newly stored file‘s Document ID
echo $storedfile;
findOne 与 get 类似,get 只能通过id取出文件,findOne可以查找文件名,日期,尺寸,以及md5值。
<?php
$connection = new MongoClient( "mongodb://neo:chen@192.168.6.1" );
$db = $connection->test;
$grid = $db->getGridFS();
$file = $grid->findOne("/etc/passwd");
echo $file->getBytes();
指定 collections
<?php $images = $db->mydb->getGridFS(‘images‘); $image = $images->findOne(‘jwage.png‘); header(‘Content-type: image/png;‘); echo $image->getBytes(); ?>
findOne一直只返回一条数据,find可以返回结果集,实现遍历文件。
<?php
$connection = new MongoClient( "mongodb://neo:chen@192.168.6.1" );
$db = $connection->test;
$grid = $db->getGridFS();
$files = $grid->find();
foreach ($files as $file){
print_r($file);
}
本文节选自《Netkiller PHP 手札》
http://netkiller.github.io/php/index.html
PHP + MongoDB + GridFS
标签: