php+MongoDB+vue实现用户注册登录认证增删改查、聚合、索引管理、模糊搜索和批量写入操作日记示例代码
代码语言:php
所属分类:其他
代码描述:php+MongoDB+vue实现用户注册登录认证增删改查、聚合、索引管理、模糊搜索和批量写入操作日记示例代码,封装了一个强大的 MongoDBHandler 类,实现了对 MongoDB 数据库的连接(包含用户名密码认证)和全方位的操作,包括增删改查、聚合、索引管理、模糊搜索和批量写入等。通过 RESTful API 接口,它提供了用户注册、登录以及内容条目的管理功能。 前端则内嵌了基于 Vue.js、Axios 和 Tailwind CSS 构建的现代化单页应用界面。用户可以在这个界面上直观地进行所有
代码标签: php MongoDB vue 用户 注册 登录 认证 增删 改查 聚合 索引 管理 模糊 搜索 批
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
<?php
// app.php - 单文件演示:MongoDB 常用操作 + Vue 前端
// 注意:生产请改用更安全认证与 CSRF 防护
// ------------------ 配置 ------------------
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
// --- 修改为你的 MongoDB 连接信息 ---
define('MONGO_HOST', '127.0.0.1');
define('MONGO_PORT', '27017');
define('MONGO_USER', ''); // <-- 在此填写您的 MongoDB 用户名
define('MONGO_PASS', ''); // <-- 在此填写您的 MongoDB 密码
define('MONGO_AUTH_DB', 'admin'); // <-- 认证数据库,通常是 'admin'
define('DB_NAME', ''); // <-- 您的数据库名
// --- 安全设置 ---
// 根据上面的配置构建完整的 MongoDB 连接 URI
// 格式: mongodb://user:pass@host:port/dbname?authSource=authdb
define('MONGO_URI', sprintf(
'mongodb://%s:%s@%s:%s/%s',
rawurlencode(MONGO_USER),
rawurlencode(MONGO_PASS),
MONGO_HOST,
MONGO_PORT,
DB_NAME,
MONGO_AUTH_DB
));
// 集合名
define('COL_USERS', 'users');
define('COL_ENTRIES', 'entries');
// ------------------ MongoDBHandler 类(封装) ------------------
class MongoDBHandler {
private $manager;
private $dbName;
private $collection;
public function __construct($uri = MONGO_URI, $dbName = DB_NAME, $collection = COL_ENTRIES) {
$this->dbName = $dbName;
$this->collection = $collection;
try {
// 使用包含认证信息的 URI 创建 Manager 实例
$this->manager = new MongoDB\Driver\Manager($uri);
} catch (MongoDB\Driver\Exception\Exception $e) {
throw new Exception("MongoDB connection failed: " . $e->getMessage());
}
}
public function setCollection($name) { $this->collection = $name; }
public function getNamespace() { return "{$this->dbName}.{$this->collection}"; }
// 将 driver 返回的 doc/stdClass 转成数组并把 _id 转为 id string
private function docToArray($doc) {
if ($doc === null) return null;
$arr = json_decode(json_encode($doc), true);
if (isset($arr['_id'])) {
if (is_array($arr['_id']) && isset($arr['_id']['$oid'])) {
$arr['id'] = $arr['_id']['$oid'];
} else {
$arr['id'] = (string)$arr['_id'];
}
}
// 把 MongoDB 日期格式化为 ISO8601 字符串(若存在 $date)
foreach (['createdAt','updatedAt'] as $k) {
if (isset($arr[$k]) && is_array($arr[$k]) && isset($arr[$k]['$date'])) {
$d = $arr[$k]['$date'];
if (is_numeric($d)) $arr[$k] = date('c', $d/1000);
else $arr[$k] = $d;
}
}
return $arr;
}
// insert one: 返回 ObjectId 字符串
public function insertOne(&$doc) {
$bulk = new MongoDB\Driver\BulkWrite();
if (!isset($doc['createdAt'])) $doc['createdAt'] = new MongoDB\BSON\UTCDateTime();
if (!isset($doc['updatedAt'])) $doc['updatedAt'] = new MongoDB\BSON\UTCDateTime();
$oid = $bulk->insert($doc);
$this->manager->executeBulkWrite($this->getNamespace(), $bulk);
return (string)$oid;
}
// insert many: 返回 ids
public function insertMany(array $docs) {
$bulk = new MongoDB\Driver\BulkWrite();
$ids = [];
$now = new MongoDB\BSON\UTCDateTime();
foreach ($docs as $doc) {
if (!isset($doc['createdAt'])) $doc['createdAt'] = $now;
if (!isset($doc['updatedAt'])) $doc['updatedAt'] = $now;
$ids[] = (string)$bulk->insert($doc);
}
$this->manager->executeBulkWrite($this->getNamespace(), $bulk);
return $ids;
}
// find (支持 options: skip, limit, sort, projection)
public function find($filter = [], $options = []) {
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $this->manager->executeQuery($this->getNamespace(), $query);
$res = [];
foreach ($cursor as $doc) $res[] = $this->docToArray($doc);
return $res;
}
// findOne
public function findOne($filter = [], $options = []) {
$opts = array_merge($options, ['limit'=>1]);
$query = new MongoDB\Driver\Query($filter, $opts);
$cursor = $this->manager->executeQuery($this->getNamespace(), $query);
$arr = $cursor->toArray();
if (count($arr)===0) return null;
return $this->docToArray($arr[0]);
}
// 模糊正则查询
public function findLike($field, $keyword, $options = []) {
$filter = [$field => new MongoDB\BSON\Regex($keyword, 'i')];
return $this->find($filter, $options);
}
// 多条件查询(and/or)
public function findMulti(array $conditions, $type='and', $options = []) {
$filter = ($type==='or') ? ['$or'=>$conditions] : ['$and'=>$conditions];
return $this->find($filter, $options);
}
// update ($set)
public function updateOne($filter, $data, $options = ['multi'=>false, 'upsert'=>false]) {
$bulk = new MongoDB\Driver\BulkWrite();
$data['updatedAt'] = new MongoDB\BSON\UTCDateTime();
$bulk->update($filter, ['$set'=>$data], $options);
$res = $this->manager->executeBulkWrite($this->getNamespace(), $bulk);
return ['matched'=>$res->getMatchedCount(),'modified'=>$res->getModifiedCount(),'upserted'=>$res->getUpsertedCount()];
}
// update with operators (e.g. $inc, $push, $pull, $addToSet)
public function updateOperators($filter, $operators, $options = ['multi'=>false, 'upsert'=>false]) {
$bulk = new MongoDB\Driver\BulkWrite();
if (!isset($operators['$set'])) $operators['$set'] = [];
$operators['$set']['updatedAt'] = new MongoDB\BSON\UTCDateTime();
$bulk->update($filter, $operators, $options);
$res = $this->manager->executeBulkWrite($this->getNamespace(), $bulk);
return ['matched'=>$res->getMatchedCount(),'modified'=>$res->getModifiedCount()];
}
// replace one
public function replaceOne($filter, $replacement, $options = ['upsert'=>false]) {
$bulk = new MongoDB\Driver\BulkWrite();
$replacement['updatedAt'] = new MongoDB\BSON\UTCDateTime();
$bulk->replace($filter, $replacement, $options);
$res = $this->manager->executeBulkWrite($this->getNamespace(), $bulk);
return ['matched'=>$res->getMatchedCount(),'modified'=>$res->getModifiedCount()];
}
// delete one/many
public function deleteOne($filter) {
$bulk = new MongoDB\Driver\BulkWrite();
$bulk->delete($filter, ['limit'=>1]);
$res = $this->manager->executeBulkWrite($this->getNamespace(), $bulk);
return $res->getDeletedCount();
}
public function deleteMany($filter) {
$bulk = new MongoDB\Driver\BulkWrite();
$bulk->delete($filter, ['limit'=>0]);
$res = $this->manager->executeBulkWrite($this->getNamespace(), $bulk);
return $res->getDeletedCount();
}
// aggregate pipeline
public function aggregate(array $pipeline) {
$command = new MongoDB\Driver\Command([
'aggregate' => $this->collection,
'pipeline' => $pipeline,
'cursor' => new stdClass()
]);
$cursor = $this->manager->executeCommand($this->dbName, $command);
$res = [];
foreach ($cursor as $doc) $res[] = $this->docToArray($doc);
return $res;
}
// distinct
public function distinct($key, $filter = []) {
$command = new MongoDB\Driver\Command(['distinct'=>$this->collection,'key'=>$key,'query'=>$filter]);
$cursor = $this->manager->executeCommand($this->dbName, $command);
$arr = $cursor->toArray();
return isset($arr[0]->values) ? $arr[0]->values : [];
}
// count
public function count($filter = []) {
$command = new MongoDB\Driver\Command(['count'=>$this->collection,'query'=>$filter]);
$cursor = $this->manager->executeCommand($this->dbName, $command);
$arr = $cursor->toArray();
return isset($arr[0]->n) ? $arr[0]->n : 0;
}
// create index
public function createIndex($keys, $options = []) {
$cmd = new MongoDB\Driver\Command([
'createIndexes' => $this->collection,
'indexes' => [[
'key' => $keys,
'name' => $options['name'] ??.........完整代码请登录后点击上方下载按钮下载查看















网友评论0