首頁  >  文章  >  後端開發  >  一個php7+mongodb三方類別的介紹

一個php7+mongodb三方類別的介紹

不言
不言原創
2018-09-10 14:43:222950瀏覽

這篇文章帶給大家的內容是關於一個php7 mongodb三方類的介紹 ,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。

因為專案需要,把專案升級到了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());

更新一條

$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')));

刪除一條

$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);
}

相關推薦:

#詳情php7如何實作MongoDB模糊查詢

#php實作的mongodb操作類,php實作mongodb

#

以上是一個php7+mongodb三方類別的介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn