webiny /mongo
Webiny Mongo 组件
v1.6.1
2017-09-29 08:12 UTC
Requires
- php: ^7
- mongodb/mongodb: ~1.0
- webiny/config: ~1.6
- webiny/service-manager: ~1.6
- webiny/std-lib: ~1.6
Requires (Dev)
- mybuilder/phpunit-accelerator: dev-master
- phpunit/phpunit: ~6
README
Mongo 组件用于与 MongoDB 数据库交互。
安装组件
使用 Composer 安装组件是最佳方式。
composer require webiny/mongo
要获取包的附加版本,请访问Packagist 页面。
配置 Mongo 服务
推荐使用 Mongo 的方式是通过定义一个 Mongo 服务。以下是一个定义服务的示例
Mongo: Services: Webiny: Class: \Webiny\Component\Mongo\Mongo Arguments: Uri: 127.0.0.1:27017 UriOptions: [] DriverOptions: [] CollectionPrefix: 'MyDatabase_' Calls: - [selectDatabase, [MyDatabase]] Driver: \Webiny\Component\Mongo\Bridge\MongoDb
集合前缀将自动添加到所有数据库查询中。
更多信息请参见:mongodb/mongo-php-library
定义完你的 Mongo 服务(在大多数情况下你只需要一个,但你可以定义任意多个)后,你可以通过使用 MongoTrait
来访问你的 Mongo 服务
class MyClass { use MongoTrait; public function test(){ // MongoTrait uses `Webiny` as a default service name $this->mongo()->getCollectionNames(); // If you have specified your own service name, pass it to mongo method $this->mongo('MyMongo')->getCollectionNames(); } }
结果类
ResultClass
用于包装所有 Mongo 命令的结果。这允许我们在未来Mongo响应结构发生变化时有一个兼容层,同时也允许任何开发者扩展这个类,并为处理 mongo 响应标志添加自定义方法。
索引
目前 Mongo 组件支持 3 种类型的索引
- 单索引
- 复合索引
- 文本索引
要在你的集合上创建索引
// Create a unique single index object $index = new SingleIndex('Name', 'name', false, true); // Use mongo trait to create index on your collection $this->mongo()->createIndex('MyCollection', $index);
资源
要运行单元测试,你需要使用以下命令
$ cd path/to/Webiny/Component/Mongo/
$ composer.phar install
$ phpunit
确保你在 Tests\ExampleConfig.yaml
中设置了你的 MongoDb 驱动设置。