MongoDB 教程索引 MongoDB 教程一: 安装和使用 (Mongodb启动命令mongod参数说明) MongoDB 教程二: 添加,…
PHP操作远程mongodb数据库, MongoDB PHP Library, php connects with remote MongoDB
MongoDB PHP Library
项目地址:https://github.com/mongodb/mongo-php-library
官网手册:https://docs.mongodb.com/php-library/master/tutorial/crud/
php driver for mongodb : 安装mongodb的php驱动:Ubuntu: 安装MongoDB, Install MongoDB With Apache2, PHP 7.2 Support On Ubuntu 16.04 / 17.10 / 18.04
官网可视化工具:https://www.mongodb.com/download-center?initial=true&from=dcv2#community
Installation 安装库
composer require mongodb/mongodb
不知道composer是啥的同学,可以移步到:PHP: Composer 依赖管理 Composer Cheat Sheet for developers 安装和用法
这个库不可以直接使用,需要php mongodb driver的支持,如果没有安装mongodb,请移步到:Ubuntu: 安装MongoDB, Install MongoDB With Apache2, PHP 7.2 Support On Ubuntu 16.04 / 17.10 / 18.04 (其他非ubuntu系统,可以参考:Windows,Mac OSX)
PHP-mongo-php-library使用
连接
//连接本地服务 $client = new MongoDB\Client('mongodb://127.0.0.1:27017'); //选择数据库和集合 $collection = $client->selectCollection('DatebaseName', 'collectionName'); //这个库同时支持mongo拓展的写法. //$collection = $client->DatebaseName->collectionName;
单条插入 :
insertOne
方法将单个文档插入到MongoDB中,并返回一个实例,使用getInsertedId
可以获取插入文档的id , mongodb会自动生_id
字段,为24位随机字符串,同时,用户也可以指定生成原生语句为
db.user.insertOne({'name':'JustCode'})
$user = array('name'=>'JustCode','sex'=>'male'); //执行并返回实例 $result = $collection->insertOne($user); //拿到返回的_id $id= $result->getInsertedId(); //返回值:5af53f89804c044a340018f2
批量插入:跟mysql的批量原理相同,组装成多维数组.和单条插入的函数相仿insertMany
,getInsertedIds
原生语句为db.user.insertMany([{'name':'学无止境'},{'name':'JustCode'}])
$users = array(array('name'=>'学无止境','sex'=>'male'),array('name'=>'JustCode','sex'=>'male')); $result = $collection->insertMany($users); $ids_info= $result->getInsertedIds(); //拿到插入的个数 $count = $result->getInsertedCount(); /** //返回值: array(2) { [0]=> object(MongoDB\BSON\ObjectId)#11 (1) { ["oid"]=> string(24) "5af548d3804c044a340018f8" } [1]=> object(MongoDB\BSON\ObjectId)#14 (1) { ["oid"]=> string(24) "5af548d3804c044a340018f9" } } */
需要注意的是批量返回的并不是string类型的id了,而是一个非常复杂的结构,如果我们想要以数组形式拿到他的_id,我们可以使用一下函数
foreach($ids_info as $value){ $ids [] = $value->__toString(); } /** //格式为: array(2) { [0]=> string(24) "5af54ead804c044a34001920" [1]=> string(24) "5af54ead804c044a34001921" } */
查询
单个查询:findOne
,相当于sql语句的limit 1
原生语句:db.user.findOne({"_id":ObjectId("5af5553f804c044a34001922")})
//由于储存的`_id`字段是一个BSON类型的object,所以要按_id字段来查的话,要先进行类型转换 $mongo_id = new MongoDB\BSON\ObjectId('5af5553f804c044a34001922'); //查询执行 $info = $collection->findOne(array('_id'=>$mongo_id)); //如果没有找到,返回值为null //返回值是一个对象,这里我们可以将他强制类型转换`$info = (array)$info` /** object(MongoDB\Model\BSONDocument)#22 (1) { ["storage":"ArrayObject":private]=> array(4) { ["_id"]=> object(MongoDB\BSON\ObjectId)#21 (1) { ["oid"]=> string(24) "5af5553f804c044a34001922" } ["name"]=> string(5) "suhua" ["age"]=> int(26) ["sex"]=> string(3) "男" } } */
多个查询:find
多个查询有两个数组参数,第一个是查询的条件,第二个是选项
$info = $collection->find(array('name'=>'JustCode')); //第一个数组的查询条件要注意下`$gt`这是查询选择器,表示大于 //第二个数组的选项意义为:`skip`跳过0条数据,`limit`查询10条数据,`sort`按age字段正序排序(1为正序,-1为倒序) $info = $collection->find(array('name'=>'JustCode','age'=>array('$gt'=>'1')),array('skip'=>0,'limit'=>10,'sort'=>array('age'=>1))); //这时请注意,多个查询返回的是游标(Cursor),需要的进行处理 //您可以用函数转换 $info_array = $info->toArray(); //也可以用foreach迭代该对象 foreach($info as $value){ $info_array [] = $value; }
如果是查询的json结构的多维数组下的字段,可以用点链接的方式来查询,例如:
查询下面json中 breadcrumbs 下的 cid是否是26
{ "_id":"5b3fbd65de0aee18b88a31f2", "rating":"0", "breadcrumbs":[ { "url":"https:\/\/www.aliexpress.com\/category\/26\/toys-hobbies.html", "name":"Toys & Hobbies", "cid":"26" }, { "url":"https:\/\/www.aliexpress.com\/category\/200003225\/dolls-stuffed-toys.html", "name":"Dolls & Stuffed Toys", "cid":"200003225" }, { "url":"https:\/\/www.aliexpress.com\/category\/200002644\/movies-tv.html", "name":"Movies & TV", "cid":"200002644" } ], "product_id":"32792958064" }
那么可以执行:
$data = $collection>find(array('breadcrumbs.cid'=>'26'), array('limit' => 10));
合计
MongoDB\Collection::count
function count($filter = [], array $options = []): integer
This method has the following parameters:
Parameter | Type | Description |
---|---|---|
$filter |
array | object | Optional. 指定筛选条件 |
$options |
array | Optional. 指定所需选项的数组 |
更新
单条更新updateOne
多条更新updateMany
单个更新和多个更新的用法一模一样,但是要注意的是他的操作符和选项
//update方法有三个数组参数 //第一个数组是查询条件 //第二数组是更新操作符,例如下面的`array('$set'=>array('age'=>'23'))`,意义为:更改age字段为23 //第三个数组是选项,可以选择各种参数,例如下面的`array('upsert'=>true)`,意义为当能查询到就进行更改,如果没有查询到就进行新增操作 $result = $collection->updateOne(array('name'=>'JustCode'),array('$set'=>array('age'=>'23')),array('upsert'=>true)); /** 原生语句 db.user.updateOne( { "name": "justcode" }, {$set: { "age": "123" }}, { upsert: true } ) */
单个删除
deleteOne
原生语句:
db.users.deleteOne( { name: "JustCode" } )
多个删除
deleteMany
原生语句:
db.users.deleteMany( { name: "JustCode" } )
单个删除和多个删除的用法一模一样,只是单个删除只删除查询到的第一条数据,而多个删除则删除匹配到的所有数据
//单个删除 $result = $collection->deleteOne(array('name'=>'JustCode')); //多个删除 $result = $collection->deleteMany(array('name'=>'JustCode')); //拿到删除数据的条数 $count = $result->getDeletedCount();
集装成类(抛砖引玉)
<?php /** * @filesource : mongodb.php * @Author : GLS * @copyright : Copyright (C) 2010-2012 GLS IT Studio NY * @access : gotodiscuss@gmail.com * @version : Created on Dec 6, 2010 10:12:19 AM * @Github : https://github.com/phpish`````````````````````````````````````````````````` * */ defined('BASEPATH') or die('Restricted access'); include_once rtrim(dirname(__FILE__), '/').'/vendor/autoload.php'; class Mongodb { private $host; private $port = 27017; private $username; private $password; private $dbname; private $table; private $client; private $collection; private $mongodb_link; function __construct($info = array()) { $this->host = $info['host'] ?? false; $this->port = $info['port'] ?? 27017; $this->username = $info['username'] ?? false; $this->password = $info['password'] ?? false; $this->dbname = $info['dbname'] ?? false; $this->table = $info['table'] ?? false; $this->mongodb_link = $info['link'] ?? false; if(($this->host AND $this->username AND $this->username) OR $this->mongodb_link) { //连接本地服务 $mongodb_link = $info['link'] ?? $this->username.':'.$this->password.'@'.$this->host.':'.$this->port; $this->client = new MongoDB\Client('mongodb://'.str_ireplace('mongodb://', '', $mongodb_link)); } return $this; } function collection($table = '', $dbname = '') { if($table) $this->table = $table; if($dbname) $this->dbname = $dbname; //选择数据库和集合 if($this->dbname AND $this->table) $this->collection = $this->client->{$this->dbname}->{$this->table}; return $this; } function get() { return $this->collection; } function client() { return $this->client; } // $data = array('name'=>'justcode','sex'=>'male'); function insert($data = array(), $table = '', $dbname = '') { if($table OR $dbname) $this->collection($table, $dbname); $output = false; if($data) { $rv = array_filter($data,'is_array'); if(count($rv)>0) $output = $this->multi_insert($data, $table, $dbname); else { $result = $this->collection->insertOne($data); $output = $result->getInsertedId(); } } return $output; } // $data = array(array('name'=>'justcode','sex'=>'male'),array('name'=>'DullCat','sex'=>'male')); function multi_insert($data = array(), $table = '', $dbname = '') { if($table OR $dbname) $this->collection($table, $dbname); $output = false; if($data) { $result = $this->collection->insertMany($data); // $ids_info = $result->getInsertedIds(); // foreach($ids_info as $value){ // $ids [] = $value->__toString(); // } //拿到插入的个数 $output = $result->getInsertedCount(); } return $output; } //如果没有找到,返回值为null //返回值是一个对象,这里我们可以将他强制类型转换`$info = (array)$info` function find_by_id($id = '', $table = '', $dbname = '') { if($table OR $dbname) $this->collection($table, $dbname); $output = false; if($id) { $mongo_id = new MongoDB\BSON\ObjectId($id); $output = $this->collection->findOne(array('_id'=>$mongo_id)); } return $output; } // $data = array('name'=>'DullCat') //第一个数组的查询条件要注意下`$gt`这是查询选择器,表示大于 //第二个数组的选项意义为:`skip`跳过0条数据,`limit`查询10条数据,`sort`按age字段正序排序(1为正序,-1为倒序) // $data = array('name'=>'justcode','age'=>array('$gt'=>'1')),array('skip'=>0,'limit'=>10,'sort'=>array('age'=>1)) //多个查询有两个数组参数,第一个是查询的条件,第二个是选项 function find($where = array(), $options = array(), $table = '', $dbname = '') { if($table OR $dbname) $this->collection($table, $dbname); $info = $this->collection->find($where, $options); $output = $info->toArray(); return $output; } //计算合计 MongoDB\Collection::count //function count($filter = [], array $options = []): integer function count($where = array(), $options = array(), $table = '', $dbname = '') { if($table OR $dbname) $this->collection($table, $dbname); return $this->collection->count($where, $options); } //update方法有三个数组参数 //第一个数组是查询条件 //第二数组是更新操作符,例如下面的`array('$set'=>array('age'=>'23'))`,意义为:更改age字段为23 //第三个数组是选项,可以选择各种参数,例如下面的`array('upsert'=>true)`,意义为当能查询到就进行更改,如果没有查询到就进行新增操作 /** 原生语句 db.user.updateOne( { "name": "dullcat" }, {$set: { "age": "123" }}, { upsert: true } ) */ function update($where = array(), $data = array(), $options = array(), $table = '', $dbname = '') { if($table OR $dbname) $this->collection($table, $dbname); $output = false; if($where AND $data) $output = $this->collection->updateOne($where, $data, $options); return $output; } function multi_update($where = array(), $data = array(), $options = array(), $table = '', $dbname = '') { if($table OR $dbname) $this->collection($table, $dbname); $output = false; if($where AND $data) $output = $this->collection->updateMany($where, $data, $options); return $output; } // 单个删除deleteOne // 原生语句:db.users.deleteOne( { name: "justcode" } ) // 多个删除deleteMany // 原生语句:db.users.deleteMany( { name: "justcode" } ) // 单个删除和多个删除的用法一模一样,只是单个删除只删除查询到的第一条数据,而多个删除则删除匹配到的所有数据 function delete($where = array(), $table = '', $dbname = '') { if($table OR $dbname) $this->collection($table, $dbname); $output = false; if($where) $output = $this->collection->deleteOne($where); return $output; } function multi_delete($where = array(), $table = '', $dbname = '') { if($table OR $dbname) $this->collection($table, $dbname); $output = false; if($where) $output = $this->collection->deleteMany($where); return $output; } }
用法:
#方法一,引用自定义方法 $mongo = new Mongodb(array('link' => 'mongodb://username:password@host:port')); $mongo->collection('table_name', 'db_name'); $data = $mongo->find([], ['limit'=>10]); #方法二, 引用collection $mongo = new Mongodb(array('link' => 'mongodb://username:password@host:port')); $db = $mongo->collection('table_name', 'db_name')->get(); $data = $db->find(); // 可以调用任何原生方法
Query Selectors
Comparison
For comparison of different BSON type values, see the specified BSON comparison order.
Name | Description |
---|---|
$eq |
Matches values that are equal to a specified value. |
$gt |
Matches values that are greater than a specified value. |
$gte |
Matches values that are greater than or equal to a specified value. |
$in |
Matches any of the values specified in an array. |
$lt |
Matches values that are less than a specified value. |
$lte |
Matches values that are less than or equal to a specified value. |
$ne |
Matches all values that are not equal to a specified value. |
$nin |
Matches none of the values specified in an array. |
Logical
Name | Description |
---|---|
$and |
Joins query clauses with a logical AND returns all documents that match the conditions of both clauses. |
$not |
Inverts the effect of a query expression and returns documents that do not match the query expression. |
$nor |
Joins query clauses with a logical NOR returns all documents that fail to match both clauses. |
$or |
Joins query clauses with a logical OR returns all documents that match the conditions of either clause. |
Element
Name | Description |
---|---|
$exists |
Matches documents that have the specified field. |
$type |
Selects documents if a field is of the specified type. |
Evaluation
Name | Description |
---|---|
$expr |
Allows use of aggregation expressions within the query language. |
$jsonSchema |
Validate documents against the given JSON Schema. |
$mod |
Performs a modulo operation on the value of a field and selects documents with a specified result. |
$regex |
Selects documents where values match a specified regular expression. |
$text |
Performs text search. |
$where |
Matches documents that satisfy a JavaScript expression. |
Geospatial
Name | Description |
---|---|
$geoIntersects |
Selects geometries that intersect with a GeoJSON geometry. The 2dsphere index supports$geoIntersects . |
$geoWithin |
Selects geometries within a bounding GeoJSON geometry. The 2dsphere and 2d indexes support $geoWithin . |
$near |
Returns geospatial objects in proximity to a point. Requires a geospatial index. The 2dsphereand 2d indexes support $near . |
$nearSphere |
Returns geospatial objects in proximity to a point on a sphere. Requires a geospatial index. The 2dsphere and 2d indexes support $nearSphere . |
Array
Name | Description |
---|---|
$all |
Matches arrays that contain all elements specified in the query. |
$elemMatch |
Selects documents if element in the array field matches all the specified $elemMatch conditions. |
$size |
Selects documents if the array field is a specified size. |
Bitwise
Name | Description |
---|---|
$bitsAllClear |
Matches numeric or binary values in which a set of bit positions all have a value of 0 . |
$bitsAllSet |
Matches numeric or binary values in which a set of bit positions all have a value of 1 . |
$bitsAnyClear |
Matches numeric or binary values in which any bit from a set of bit positions has a value of 0 . |
$bitsAnySet |
Matches numeric or binary values in which any bit from a set of bit positions has a value of 1 . |
Projection Operators
Name | Description |
---|---|
$ |
Projects the first element in an array that matches the query condition. |
$elemMatch |
Projects the first element in an array that matches the specified $elemMatch condition. |
$meta |
Projects the document’s score assigned during $text operation. |
$slice |
Limits the number of elements projected from an array. Supports skip and limit slices. |
当然,还有很多功能我都没讲到,比如常用的aggregate
聚合,这些就留给大家去阅读官方文档吧
参考文档:
官网CRUD操作:https://docs.mongodb.com/php-library/master/tutorial/crud/
查询选择器:https://docs.mongodb.com/manual/reference/operator/query/
更新操作符:https://docs.mongodb.com/manual/reference/operator/update/#update-operators
Aggregation Pipeline:https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/
本文:PHP操作远程mongodb数据库, MongoDB PHP Library, php connects with remote MongoDB
Comments
$comment