Due to project needs, the project has been upgraded to php7
. But after upgrading, I found that the mongo
extension cannot be used. php7.0
The above only supports mongodb
extensions. The mongodb
extended driver is more complicated and verbose to use than the monmgo
extension. I've been looking for it online for a long time. Finally found a relatively simple mongodb
class. The syntax is similar to mongo
. Clear and natural.
Project addresshttps://github.com/mongodb/mongo-php-library
Because the project was contributed by foreign friends. So there is no clear document that can be read. Here are some commonly used methods.
Get instance
$uri = "mongodb://username:password@host/database"; $client = new \MongoDB\Client($uri);
Get collection
$collection = $client->selectCollection('test','test');
Get a piece of data
$data = $collection->findOne(['id'=>1]);
Get multiple pieces of data
$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);
Remove duplicates
$fileName = 'name'; $where = ['id' => ['$lt' => 100]] $ret = $this->collection->distinct($fileName,$where);
Insert a piece of data
$data = array( 'id' => 2, 'age' => 20, 'name' => '张三' ); $ret = $collection->insertOne($data); $id=$ret->getInsertedId();
Batch insert
$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());
Update one item
$ret = $collection->updateOne(array('id' => 2), array('$set' => array('age' => 56)));
Update multiple items
$ret = $collection->updateMany(array('id' => ['$gt' => 1]), array('$set' => array('age' => 56, 'name' => 'x')));
Delete one item
$ret = $collection->deleteOne(array('id' => 2));
Delete multiple items
$collection->deleteMany(array('id' => array('$in' => array(1, 2))));
aggregation
$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); }