一.对mongodb的操作
1.连接数据库
$manager = new MongoDB\Driver\Manager("mongodb://127.0.0.1:27017");
2.条件查询
$filter = [
'name' => $formValue->userName,
'password' => $formValue->userPassword
];
$options = [
'projection' => ['_id' => 0],
'sort' => ['name' => 1],
];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $GLOBALS['manager']->executeQuery('img_dsc.user', $query);
3. 插入
$bulk = new MongoDB\Driver\BulkWrite();
$bulk->insert(['_id' => new MongoDB\BSON\ObjectID,'name' => $formValue->userName, 'password'=>$formValue->userPassword]);
$GLOBALS['manager']->executeBulkWrite('img_dsc.user', $bulk);
4.分页查询
$filter = [
'name' => $formValue->userName,
'password' => $formValue->userPassword
];
$options = [
'projection' => ['_id' => 0],
'sort' => ['name' => 1],
'skip' => $group*20, // 查询的起始位置 数据库最开始从0开始计算
'limit' => 20 // 查询的数量
];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $GLOBALS['manager']->executeQuery('img_dsc.user', $query);
5.删除
function delImg($id){
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulk = new MongoDB\Driver\BulkWrite;
$fileId = new MongoDB\BSON\ObjectId($id -> id);
$bulk->delete(['x' => 1], ['limit' => 1]); // limit 为 1 时,删除第一条匹配数据
$bulk->delete(['x' => 2], ['limit' => 0]); // limit 为 0 时,删除所有匹配数据
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('test.sites', $bulk, $writeConcern);
}
二.gridfs
1.在项目根目录使用composer 下载mongodb/mongodb
composer require mongodb/mongodb
2.在php文件里引入
require '../../vendor/autoload.php';
3.插入上传的图片
function uploadFile($file){
//链接MongoDB
$client=new MongoDB\Client();//连接数据库
$gridFsCollection=$client->img_dsc->selectGridFSBucket();//这里只指定了databases,collection按照默认的来就行
$fileId = new MongoDB\BSON\ObjectId;
$fileName=$file->name;//文件名
$fileValue=fopen($file -> tmp_name,'rb');//读取文件存入内存
//存储文件流图片
$gridFsResult=$gridFsCollection->uploadFromStream($fileId,$fileValue); //返回fs.file中的_id
//打印ID
exit($gridFsResult);
}
4.查询
function queryFile(){
$fileId = new MongoDB\BSON\ObjectId('608a9618171e00000c001085');
$bucket = (new MongoDB\Client())->img_dsc->selectGridFSBucket();
$stream = $bucket->openDownloadStream($fileId);
$metadata = $bucket->getFileDocumentForStream($stream);
return $metadata;
}
5. 将图片读出,由二进制,转为base64码
function downFile(){
$bucket = (new MongoDB\Client)->img_dsc->selectGridFSBucket();
$fileId = new MongoDB\BSON\ObjectId('608a9618171e00000c001085');
$stream = $bucket->openDownloadStream($fileId);
$contentString=stream_get_contents($stream);
// 转为base64码
return chunk_split(base64_encode($contentString));
}
6. 删除
function delImg($id){
$fileId = new MongoDB\BSON\ObjectId;
$fileId = new MongoDB\BSON\ObjectId($id -> id);
$bucket = (new MongoDB\Client)->test->selectGridFSBucket();
$bucket->delete($fileId);
}
版权属于:小小窝/禾下月
本文链接:https://hxyxyz.top/index.php/%E6%8A%80%E6%9C%AF/308.html
本站文章采用 知识共享署名4.0 国际许可协议 进行许可,请在转载时注明出处及本声明!