php slaveok_MongoDb - ThinkPHP 5.1 完全开发手册

使用Mongo之前,需要装PHP的mongo扩展,访问 http://pecl.php.net/package/mongodb ,选择最新的版本即可,然后选择你的PHP版本对应的扩展。

然后使用Composer安装扩展包:

composer require topthink/think-mongo

接下来,需要修改数据库配置文件中的相关参数:

// 数据库类型

'type' => '\think\mongo\Connection',

// 设置查询类

'query' => '\think\mongo\Query',

// 服务器地址

'hostname' => '127.0.0.1',

// 集合名

'database' => 'demo',

// 用户名

'username' => '',

// 密码

'password' => '',

// 端口

'hostport' => '',

默认安装的mongodb是没有用户名和密码的,可以留空。如果你的服务器安装的mongodb提供了用户名和密码认证,请自行修改。MongoDb一样支持分布式设置,设置方法和Mysql的分布式设置一致。

关于主键

MongoDb会自动添加_id字段而且作为主键,该主键数据是一个MongoDB\BSON\ObjectID对象实例。

为了方便查询,系统做了封装,该主键的值可以直接当作字符串使用,因此下面的查询是有效的:

// 查询操作

$user = Db::table('user')

->where('_id','589461c0fc122812b4007411')

->find();

// 或者直接使用

$user = Db::table('user')

->find('589461c0fc122812b4007411');

为了保持和Mysql一致的主键命名习惯,系统提供了一个数据库配置参数pk_convert_id可以强制把_id转换为id进行操作。

// 强制把_id转换为id

'pk_convert_id' => true,

设置后,就可以把id当成_id来使用

// 查询操作

$user = Db::table('user')

->where('id','589461c0fc122812b4007411')

->find();

dump($user);

输出结果为:

array (size=3)

'name' => string 'thinkphp' (length=8)

'email' => string '[email protected]' (length=15)

'id' => string '589461c0fc122812b4007411' (length=24)

原来的_id已经变成id,而且是一个字符串类型。

方法变化和差异

除了常规的CURD方法之外,包括value、column、setInc、setDec、setField、paginate等方法仍然被支持,更新的时候也支持data、inc和dec方法,包括聚合查询方法也都支持。

由于数据库自身的原因,以下链式方法在MongoDb中不再支持(或者无效):

不再支持的方法

view

join

alias

group

having

union

lock

strict

sequence

force

bind

partition

针对了MongoDb的特殊性增加了如下链式操作方法:

方法

描述

skip

设置skip

awaitData

设置awaitData

batchSize

设置batchSize

exhaust

设置exhaust

modifiers

设置modifiers

noCursorTimeout

设置noCursorTimeout

oplogReplay

设置oplogReplay

partial

设置partial

maxTimeMS

设置maxTimeMS

slaveOk

设置slaveOk

tailable

设置tailable

writeConcern

设置writeConcern

并且fetchPdo方法改为fetchCursor。

Mongo原生查询

系统提供了几个基础查询方法,仅供熟悉MongoDb语法的用户使用。

query ($collection, $query)

collection:表示当前查询的集合

query:是一个\MongoDB\Driver\Query对象,详细用法可以参考官方手册

代码示例如下

$filter = [

'author' => 'bjori',

'views' => [

'$gte' => 100,

],

];

$options = [

/* Only return the following fields in the matching documents */

'projection' => [

'title' => 1,

'article' => 1,

],

/* Return the documents in descending order of views */

'sort' => [

'views' => -1

],

);

$query = new MongoDB\Driver\Query($filter, $options);

Db::query('demo.user', $query);

execute ($collection, $bulk)

collection:表示当前查询的集合

bulk:是一个\MongoDB\Driver\BulkWrite对象,详细用法可以参考官方手册

command ($command, $dbName)

command:是一个\MongoDB\Driver\Command对象,详细用法参考官方手册

dbName:当前操作的数据库名称,留空表示当前数据库

除此之外,系统还封装了一个cmd方法可以直接执行字符串格式的mongo命令,例如:

// 列出当前的集合

$collections = Db::cmd('listCollections');

更多的mongo命令参考MongoDb官方手册。

你可能感兴趣的:(php,slaveok)