php 7+mongodbの3つのクラスを推薦します

3355 ワード

プロジェクトの必要性のため、プロジェクトをphp7にアップグレードしました.しかしアップグレードしてみるとmongo拡張が使えなくなっていました.php7.0以上はmongodb拡張のみサポートされています.mongodb拡張の駆動はmonmgo拡張よりも複雑でうるさい.ネットでずいぶん探しました.やっと比較的簡潔なmongodb類を見つけた.文法はmongoとあまり違いません.くっきり
プロジェクトアドレスhttps://github.com/mongodb/mongo-php-library
プロジェクトは海外の友人が貢献したからだ.だからよく読める文書はありません.ここではよく使われる方法を整理しました.
インスタンスの取得
$uri = "mongodb://username:password@host/database";
$client = new \MongoDB\Client($uri);

コレクションの取得
$collection = $client->selectCollection('test','test');

データの取得
$data = $collection->findOne(['id'=>1]);

複数のデータの取得
$where = ['type'=>1];
$options = array(
    'projection' => array('id' => 1, 'age' => 1, 'name' => -1), //          1      -1      
    'sort' => array('id' => -1), //       
    'limit' => 10, //        
    'skip' => 0, //       
);
$data = $collection->find($where,$options)->toArray();
var_dump($data);

重さを落とす
$fileName = 'name';
$where = ['id' => ['$lt' => 100]]
$ret = $this->collection->distinct($fileName,$where);

データを挿入
$data = array(
    'id' => 2,
    'age' => 20,
    'name' => '  '
);
$ret = $collection->insertOne($data);
$id=$ret->getInsertedId();

一括挿入
$data = array(
    ['id' => 1, 'age' => 21, 'name' => '1xiaoli'],
    ['id' => 2, 'age' => 22, 'name' => '2xiaoli'],
    ['id' => 3, 'age' => 23, 'name' => '3xiaoli'],
    ['id' => 4, 'age' => 26, 'name' => '4xiaoli'],
    ['id' => 5, 'age' => 24, 'name' => '5xiaoli'],
    ['id' => 6, 'age' => 25, 'name' => '6xiaoli'],
);
$ret = $collection->insertMany($data);
#     id
var_dump($ret->getInsertedIds());

1つ更新
$ret = $collection->updateOne(array('id' => 2), array('$set' => array('age' => 56)));

複数の更新
$ret = $collection->updateMany(array('id' => ['$gt' => 1]), array('$set' => array('age' => 56, 'name' => 'x')));

1つ削除
$ret = $collection->deleteOne(array('id' => 2));

複数の削除
$collection->deleteMany(array('id' => array('$in' => array(1, 2))));

じゅうごう
$ops = [
    [
        '$match' =>['type'=>['$in'=>[2,4]]]
    ],
    [
        '$sort' => ['list.create_time' => -1]  //sort     ,         ,        
    ],
    [
        '$skip' => 0
    ],
    [
        '$limit' => 20000
    ],
];
$data = $collection->aggregate($ops);
foreach ($data as $document)
{
    var_dump($document);
}