PHP code example of zdz / mongodb-php7
1. Go to this page and download the library: Download zdz/mongodb-php7 library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
zdz / mongodb-php7 example snippets
use \MongodbPhp7\Connection;
// 配置文件- 没有填写的则按默认值来
$config = [
// 服务器地址
'host' => '127.0.0.1',
// 端口
'port' => 27017,
// 数据库名
'database' => 'test',
// 用户名
'username' => '',
// 密码
'password' => '',
// 连接dsn
'dsn' => '',
// MongoDB\Driver\Manager option参数
'option' => [],
// 主键字段
'pk' => '_id',
// 主键处理(全局) 查找和更新此主键会转化成对应的形式,如:查找 :_id = 5d71c5415c998d3dc4006832, 更新: _id 会处理成objectID类型
'pk_convert_string' => true,
// 数据库表前缀
'prefix' => '',
// 开启debug 支持: 记录最后一条指令
'debug' => true,
// 默认分页一页数量
'rows_limit' => 10
];
// 使用静态方法
$db = Connection::instance($config);
//$db = new Connection($config);
$db->setConfig('database', 'test1');
$collection = $db->collection('first'); // 配置下数据库的first集合
$collection = $db->collection('test2.first'); // 临时选择test2数据库的first集合
$count = $collection->insert($insertData, false);
$insertCount = $collection->insertAll([
[
'name' => '静香',
'age' => 10
],
[
'name' => '大熊',
'age' => 18
]
]);
$collection->where(['_id' => '5d71ee675c998d22b0004b92']);
// 多个则需要自己转化,暂没有处理
$collection->where([
'_id' => [
'$in' => [
$db->stringConvertPk('5d71ee675c998d22b0004b92'),
$db->stringConvertPk('5d71ee675c998d22b0004b92')
]
]
]);
$collection->where($where)
->upsert(true)
->update([
'name' => '测试',
'age' => [ // 年龄加1
'$inc' => 1
]
]);
$collection->where($where)->setField($field, $value);
$collection->where($where)->setInc($field, $num);
$collection->where($where)->limit(1)->delete();
$field = '_id,name,age';
// 计算字段和
$field = [
'name',
'age2',
'age2',
'ageSet' => [
'$add' => ['$age1', '$age2']
]
];
$collection->where($where)
->sort(['age' => $db::SORT_ASC]);
// 以name分组,计算年龄和
$collection->where($where)
->sort(['age' => $db::SORT_ASC])
->limit(10)
->group(['_id' => '$name', 'age' => ['$sum' => '$age']])
$collection->where($where)->find();
$collection->where($where)->find($field);
$collection->where($where)->column($field);
$collection->where($where)->count();
$collection->where($where)->sample($num);
$collection->where($where)
// ->group($group)
// ->sort($sort)
// ->limit($limit)
->page($page);