MongoDB测试案例

MongoDB requires PHP 7.0 or higher.安装php扩展不在此赘述。

1.php原生MongoDB驱动:

$manager = new MongoDB\Driver\Manager("mongodb://127.0.0.1", ['username' => 'myuser', 'password' => 'mypass', 'authSource' => 'mydb']);

$readPreference = $manager->getReadPreference();

$filter = ['tabid' => ['$lt' => 123]];
$options = [
    'sort' => ['_id' => 1],
];

$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('mydb.mycoll', $query); //第一个参数填写不对会报错:not authorized on db;别问我怎么知道的,说多了都是泪
foreach ($cursor as $document) {
    print_r($document);
}

2.composer 安装mongodb/mongodb第三方库

composer require mongodb/mongodb

测试代码:

require('./vendor/autoload.php');

$client = new MongoDB\Client(
       'mongodb://127.0.0.1',
       [
           'username' => 'myuser',
           'password' => 'mypass',
           'authSource' => 'mydb',
       ]
   );
// var_dump($client);
$collection = $client->mydb->mycoll;
$options = [
    'sort' => ['_id' => -1],
    'limit' => 1
];
$cursor = $collection->find(['tabid' => ['$gt' => 123]], $options);

foreach ($cursor as $document) {
    var_dump($document);
}

其中$client->mydb->mycoll;使用魔术发放__set()实现层层调用

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