php 7+mongodbの3つのクラスを推薦します
プロジェクトの必要性のため、プロジェクトを
プロジェクトアドレス
プロジェクトは海外の友人が貢献したからだ.だからよく読める文書はありません.ここではよく使われる方法を整理しました.
インスタンスの取得
コレクションの取得
データの取得
複数のデータの取得
重さを落とす
データを挿入
一括挿入
1つ更新
複数の更新
1つ削除
複数の削除
じゅうごう
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);
}