Yii 2 透過官方擴充套件 yiisoft/yii2-mongodb 提供原生 MongoDB 支援,包含 ActiveRecord、Query Builder、Migration 等功能。本文說明如何安裝擴充套件並設定資料庫連線元件。
composer require yiisoft/yii2-mongodb --prefer-dist
必要前提:PHP 必須安裝 mongodb PECL 擴充模組(非舊版 mongo)。
# Ubuntu/Debian pecl install mongodb echo "extension=mongodb.so" > /etc/php/7.4/mods-available/mongodb.ini phpenmod mongodb # Windows: 下載對應版本的 php_mongodb.dll 放入 ext 目錄,php.ini 加入 extension=mongodb
驗證:php -m | grep mongodb 或 phpinfo() 應顯示 mongodb 模組。
編輯 common/config/main-local.php(或對應環境設定檔):
[
'mongodb' => [
'class' => 'yii\mongodb\Connection',
'dsn' => 'mongodb://username:password@localhost:27017/database_name',
// 選項
'options' => [
'connectTimeoutMS' => 5000,
'serverSelectionTimeoutMS' => 3000,
],
],
],
];
mongodb://:協議前綴username:password@:認證資訊(若無認證可省略)localhost:27017:主機與埠號/database_name:預設資料庫名稱// Model
namespace common\models;
use yii\mongodb\ActiveRecord;
class Article extends ActiveRecord {
public static function collectionName() {
return 'article'; // 集合名稱
}
public function attributes() {
return ['_id', 'title', 'content', 'author_id', 'created_at', 'updated_at'];
}
}
// Controller / Service
$article = new Article();
$article->title = 'Yii2 + MongoDB 實戰';
$article->content = '內容...';
$article->author_id = 1001;
$article->created_at = new \MongoDB\BSON\UTCDateTime(); // 儲存為 BSON Date
$article->save();
// 查詢
$articles = Article::find()
->where(['author_id' => 1001])
->orderBy(['created_at' => SORT_DESC])
->limit(10)
->all();
ObjectId,Yii 會自動映射為字串;查詢時可直接用字串比對。UTCDateTime:儲存日期請用 \MongoDB\BSON\UTCDateTime,不要用 PHP DateTime 物件直接存入。db.article.createIndex({author_id: 1, created_at: -1})。完成上述設定後,即可在 Yii 2 專案中無縫操作 MongoDB,享受文件型資料庫的彈性結構與高效能寫入優勢!