Mongo:笔记六(php实例)

6 篇文章 0 订阅

安装扩展:

wget http://pecl.php.net/get/mongo-1.2.6.tgz
tar -zxf mongo-1.2.6.tgz
cd mongo-1.2.6
/usr/local/php/bin/phpize
./configure--with-php-config=/usr/local/php/bin/php-config
--with-php-config这个参数是告诉配置脚本php-config这个程序的路径
make&& make install

完成后,请编辑你php.ini文件增加一行
extension=mongo.so
一般默认的编译php的ini文件/usr/local/php/etc/php.ini
重启Apache打开phpinfo
看到mongo模块,证明MongoDB的php扩展安装成功。


基本步骤:

<?php

// 链接服务器
$m = new MongoClient();

// 选择一个数据库
$db = $m->comedy;

// 选择一个集合( Mongo 的“集合”相当于关系型数据库的“表”)
$collection = $db->cartoons;

// 插入一个文档(译注:“文档”相当于关系型数据库的“行”)
$document = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );
$collection->insert($document);

// 添加另一个文档,它的结构与之前的不同
$document = array( "title" => "XKCD", "online" => true );
$collection->insert($document);

// 查询集合中的所有文档
$cursor = $collection->find();

// 遍历查询结果
foreach ($cursor as $document) {
    echo $document["title"] . "\n";
}

?>


1、连接Mongo服务器

<?php
$conn = new Mongo();
#连接localhost:27017
$conn = new Mongo('localhost:22011');
#连接localhost:27017
$conn = new Mongo("mongodb://${username}:${password}@localhost:27017/blog");
#MongoDB有用户名密码并指定数据库blog

$connection = new MongoClient(); // 连接到 localhost:27017
$connection = new MongoClient( "mongodb://example.com" ); // 连接到远程服务器 (使用默认端口: 27017)
$connection = new MongoClient( "mongodb://example.com:65432" ); // 链接到远程服务器,使用自定义的端口

//针对"admin"数据库的认证
// Specifying the username and password in the connection URI (preferred)
$m = new MongoClient("mongodb://${username}:${password}@localhost");

// Specifying the username and password via the options array (alternative)
$m = new MongoClient("mongodb://localhost", array("username" => $username, "password" => $password));

//一般数据库连接
// Specifying the authentication database in the connection URI (preferred)
$m = new MongoClient("mongodb://${username}:${password}@localhost/myDatabase");

// Specifying the authentication database via the options array (alternative)
$m = new MongoClient("mongodb://${username}:${password}@localhost", array("db" => "myDatabase"));

//复制集合   要链接到一个复制,需要指定复制中的一个或多个成员,并使用 "replicaSet" 选项指定复制的名字。多个服务器用逗号分割。
// Using multiple servers as the seed list (prefered)
$m = new MongoClient("mongodb://rs1.example.com:27017,rs2.example.com:27017/?replicaSet=myReplSetName"));

// Using one server as the seed list
$m = new MongoClient("mongodb://rs1.example.com:27017", array("replicaSet" => "myReplSetName"));

// Using multiple servers as the seed list
$m = new MongoClient("mongodb://rs1.example.com:27017,rs2.example.com:27017", array("replicaSet" => "myReplSetName"));
/**

驱动会查询数据库服务器列表,然后找出主服务器。如果可以成功的链接到指定的服务器至少一个,并且可以找到主服务器,链接就会成功。如果它无法链接指定的任何一个服务器,或者找不到主服务器,会抛出一个 MongoConnectionException 类型的异常

Tip
你应该始终指定多个复制中的服务器。为了达到最大的可用性,你指定的服务器列表应该包含每一个数据中心的服务器至少一台。
如果主服务器变为不可用,会有一台次要服务器通过投票算法自动提升为主服务器(除非“投票”无法选出主服务器)。在一段时间里 (» 20-60 秒),链接无法进行写操作,此时写入会导致一个异常。 到次要服务器的链接仍然可以提供读取功能。

Note:
默认的 读取偏好 是只从主服务器读取。在自动选择新的主服务器的时间里,读取操作也会失败。
对于要求很高的读取可用性的应用,推荐使用 MongoClient::RP_PRIMARY_PREFERRED 读取偏好来确保主服务器出现问题的时候能正确的从次要服务器中读取。
当新的主服务器被选出后,尝试读写操作时,驱动会检测新的主服务器。然后链接到它,继续提供正常的功能。

次要服务器的健康状态每5秒(可以通过 mongo.ping_interval 调整),或5秒后的下一个操作执行时检查一次。驱动会在连接服务器出现错误时重新检查配置。

复制集会每60秒(可以通过 mongo.is_master_interval 调整),或在w=1的写入操作发生错误的时候检查故障并尝试恢复。

Caution
次要服务器中的操作相比主服务器有一定延迟,因此如果使用 MongoClient::RP_PRIMARY 之外的读取偏好,你的程序就必须能够正确处理过时的数据。

*/

//分片连接
// Using one server as the seed list
$m = new MongoClient("mongodb://mongos1.example.com:27017");

// Using multiple servers as the seed list
$m = new MongoClient("mongodb://mongos1.example.com:27017,mongos2.example.com:27017"));

//Unix Domain Socket支持
$m = new MongoClient("mongodb:///tmp/mongo-27017.sock");
$m = new MongoClient("mongodb://username:password@/tmp/mongo-27017.sock:0/foo");

//持久连接
$m = new MongoClient("localhost:27017", array("persist" => "x"));

?>

2、指定数据库和数据集名(表名)

<?php
$db= $conn->blog;
#选择数据库blog
$collection= $db->users;
#制定结果集(表名:users)
?>

3、插入一个文档

关联数组是能插入集合的最基本结构。 一般的“文档”结构可能是这样:

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;
$doc = array(
    "name" => "MongoDB",
    "type" => "database",
    "count" => 1,
    "info" => (object)array( "x" => 203, "y" => 102),
    "versions" => array("0.9.7", "0.9.8", "0.9.9")
);
$collection->insert( $doc );
?>


4、获取一条

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;
//{name:"user1"}==array("name"=>"user1")
//[1,2]==array(1,2);
$cursor = $collection->find();
var_dump($cursor);

$document = $collection->findOne();
var_dump( $document );
?>


5、添加多条

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

for ( $i = 0; $i < 100; $i++ )
{
    $collection->insert( array( 'i' => $i, "field{$i}" => $i * 2 ) );
}
?>


6、获取条数

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

echo $collection->count();
?>

7、foreach

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$cursor = $collection->find();
foreach ( $cursor as $id => $value )
{
    echo "$id: ";
    var_dump( $value );
}
?>

8、设置查询条件

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$query = array( 'i' => 71 );
$cursor = $collection->find( $query );

while ( $cursor->hasNext() )
{
    var_dump( $cursor->getNext() );
}
?>

9、获取子集

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$query = array( "i" => array( '$gt' => 50 ) ); //note the single quotes around '$gt'
$cursor = $coll->find( $query );

while ( $cursor->hasNext() )
{
    var_dump( $cursor->getNext() );
}
?>

10、建立索引

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$coll->ensureIndex( array( "i" => 1 ) );  // create index on "i"
$coll->ensureIndex( array( "i" => -1, "j" => 1 ) );  // index on "i" descending, "j" ascending
?>

11、更新

<?php

$sarr=array('name'=>'user1',);
$darr=array('$set'=>array('sex'=>'nv','age'=>300));
$opts=array('upsert'=>0,'multiple'=>1);
if($c1->update($sarr,$darr,$opts))

?>

12、删除

<?php 

$arr=array("name"=>"user2");
if($c1->remove($arr))

?>




SQL TO MONGO




核心类方法申明截图:


MongoClient类 (Mongo继承自MongoClient 某些方法已过时 不推荐使用) 
http://php.net/manual/zh/class.mongoclient.php#class.mongoclient

简介:PHP 和 MongoDB 的连接管理器。 这个类用于创建和管理连接。获得数据库连接对象

类摘要:

MongoClient {
/* 常量 */
const string VERSION ;
const string DEFAULT_HOST = "localhost" ;
const int DEFAULT_PORT = 27017 ;
const string RP_PRIMARY = "primary" ;
const string RP_PRIMARY_PREFERRED = "primaryPreferred" ;
const string RP_SECONDARY = "secondary" ;
const string RP_SECONDARY_PREFERRED = "secondaryPreferred" ;
const string RP_NEAREST = "nearest" ;
/* 属性 */
public boolean $connected = FALSE ;
public string $status = NULL ;
protected string $server = NULL ;
protected boolean $persistent = NULL ;
/* 方法 */
public __construct ([ string $server = "mongodb://localhost:27017" [, array $options = array("connect" => TRUE) ]] )
public bool close ([ boolean|string $connection ] )
public bool connect ( void )
public array dropDB ( mixed $db )
public MongoDB __get ( string $dbname )
public static array getConnections ( void )
public array getHosts ( void )
public array getReadPreference ( void )
public array getWriteConcern ( void )
public bool killCursor ( string $server_hash , int|MongoInt64 $id )
public array listDBs ( void )
public MongoCollection selectCollection ( string $db , string $collection )
public MongoDB selectDB ( string $name )
public bool setReadPreference ( string $read_preference [, array $tags ] )
public bool setWriteConcern ( mixed $w [, int $wtimeout ] )
public string __toString ( void )
}



MongoDB
http://php.net/manual/zh/class.mongodb.php

简介:该类的实例用于和数据库进行交互。获得数据库操作对象

类摘要:

MongoDB {
/* 常量 */
const int PROFILING_OFF = 0 ;
const int PROFILING_SLOW = 1 ;
const int PROFILING_ON = 2 ;
/* Fields */
public integer $w = 1 ;
public integer $wtimeout = 10000 ;
/* 方法 */
public array authenticate ( string $username , string $password )
public array command ( array $command [, array $options = array() ] )
public __construct ( MongoClient $conn , string $name )
public MongoCollection createCollection ( string $name [, array $options ] )
public array createDBRef ( string $collection , mixed $document_or_id )
public array drop ( void )
public array dropCollection ( mixed $coll )
public array execute ( mixed $code [, array $args = array() ] )
public bool forceError ( void )
public MongoCollection __get ( string $name )
public array getCollectionInfo ([ array $options = array() ] )
public array getCollectionNames ([ array $options = array() ] )
public array getDBRef ( array $ref )
public MongoGridFS getGridFS ([ string $prefix = "fs" ] )
public int getProfilingLevel ( void )
public array getReadPreference ( void )
public bool getSlaveOkay ( void )
public array getWriteConcern ( void )
public array lastError ( void )
public array listCollections ([ array $options = array() ] )
public array prevError ( void )
public array repair ([ bool $preserve_cloned_files = FALSE [, bool $backup_original_files = FALSE ]] )
public array resetError ( void )
public MongoCollection selectCollection ( string $name )
public int setProfilingLevel ( int $level )
public bool setReadPreference ( string $read_preference [, array $tags ] )
public bool setSlaveOkay ([ bool $ok = true ] )
public bool setWriteConcern ( mixed $w [, int $wtimeout ] )
public string __toString ( void )
}

获得mongoDB对象

<?php

$m = new MongoClient(); // 连接
$db = $m->selectDB("example");

?>
数据库名可以用 ASCII 范围内的几乎任何字符。 但是,它们不能包括 " "、".",或者是空字符串。 名称 "system" 也是被保留的。 个别特殊但有效的数据库名:"null"、"[x,y]"、"3"、"\""、 "/"。 不像集合名,数据库名是可以包含 "$" 的。


MongoCollection
http://php.net/manual/zh/class.mongocollection.php

简介:获得表操作对象

类摘要:

MongoCollection {
/* 常量 */
const int ASCENDING = 1 ;
const int DESCENDING = -1 ;
/* Fields */
public MongoDB $db = NULL ;
public integer $w ;
public integer $wtimeout ;
/* 方法 */
public array aggregate ( array $pipeline [, array $options ] )
public MongoCommandCursor aggregateCursor ( array $command [, array $options ] )
public mixed batchInsert ( array $a [, array $options = array() ] )
public __construct ( MongoDB $db , string $name )
public int count ([ array $query = array() [, int $limit = 0 [, int $skip = 0 ]]] )
public array createDBRef ( mixed $document_or_id )
public bool createIndex ( array $keys [, array $options = array() ] )
public array deleteIndex ( string|array $keys )
public array deleteIndexes ( void )
public array distinct ( string $key [, array $query ] )
public array drop ( void )
public bool ensureIndex ( string|array $key|keys [, array $options = array() ] )
public MongoCursor find ([ array $query = array() [, array $fields = array() ]] )
public array findAndModify ( array $query [, array $update [, array $fields [, array $options ]]] )
public array findOne ([ array $query = array() [, array $fields = array() [, array $options = array() ]]] )
public MongoCollection __get ( string $name )
public array getDBRef ( array $ref )
public array getIndexInfo ( void )
public string getName ( void )
public array getReadPreference ( void )
public bool getSlaveOkay ( void )
public array getWriteConcern ( void )
public array group ( mixed $keys , array $initial , MongoCode $reduce [, array $options = array() ] )
public bool|array insert ( array|object $a [, array $options = array() ] )
public array[MongoCommandCursor] parallelCollectionScan ( int $num_cursors )
public bool|array remove ([ array $criteria = array() [, array $options = array() ]] )
public mixed save ( array|object $a [, array $options = array() ] )
public bool setReadPreference ( string $read_preference [, array $tags ] )
public bool setSlaveOkay ([ bool $ok = true ] )
public bool setWriteConcern ( mixed $w [, int $wtimeout ] )
static protected string toIndexString ( mixed $keys )
public string __toString ( void )
public bool|array update ( array $criteria , array $new_object [, array $options = array() ] )
public array validate ([ bool $scan_data = FALSE ] )
}


MongoCursor
http://php.net/manual/zh/class.mongocursor.php

简介:获得游标对象

类摘要:

MongoCursor implements MongoCursorInterface , Iterator {
/* Static Fields */
static boolean $slaveOkay = FALSE ;
static integer $timeout = 30000 ;
/* 方法 */
public MongoCursor addOption ( string $key , mixed $value )
public MongoCursor awaitData ([ bool $wait = true ] )
public MongoCursor batchSize ( int $batchSize )
public __construct ( MongoClient $connection , string $ns [, array $query = array() [, array $fields = array() ]] )
public int count ([ bool $foundOnly = FALSE ] )
public array current ( void )
public bool dead ( void )
protected void doQuery ( void )
public array explain ( void )
public MongoCursor fields ( array $f )
public array getNext ( void )
public array getReadPreference ( void )
public bool hasNext ( void )
public MongoCursor hint ( mixed $index )
public MongoCursor immortal ([ bool $liveForever = true ] )
public array info ( void )
public string|int key ( void )
public MongoCursor limit ( int $num )
public MongoCursor maxTimeMS ( int $ms )
public array next ( void )
public MongoCursor partial ([ bool $okay = true ] )
public void reset ( void )
public void rewind ( void )
public MongoCursor setFlag ( int $flag [, bool $set = true ] )
public MongoCursor setReadPreference ( string $read_preference [, array $tags ] )
public MongoCursor skip ( int $num )
public MongoCursor slaveOkay ([ bool $okay = true ] )
public MongoCursor snapshot ( void )
public MongoCursor sort ( array $fields )
public MongoCursor tailable ([ bool $tail = true ] )
public MongoCursor timeout ( int $ms )
public bool valid ( void )
}

操作数据:

<?php

$cursor = $collection->find();
var_dump(iterator_to_array($cursor));

foreach ($cursor as $doc) {
    // do something to each document
}


$cursor = $collection->find()->limit(10);

// database has not yet been queried, so more search options can be added
$cursor = $cursor->sort(array("a" => 1));

var_dump($cursor->getNext());
// now database has been queried and more options cannot be added

// so this will throw an exception:
$cursor->skip(4);
?>



type (Mongo数据类型)


MongoID
http://php.net/manual/zh/class.mongoid.php

简介:获得mongo式的ID

类摘要:

MongoId {
public string $id = NULL ;
/* 方法 */
public __construct ([ string $id = NULL ] )
public static string getHostname ( void )
public int getInc ( void )
public int getPID ( void )
public int getTimestamp ( void )
public static bool isValid ( mixed $value )
public static MongoId __set_state ( array $props )
public string __toString ( void )
}

使用:

<?php

$oid=new MongoId($_GET[id]);
$arr=array("_id"=>$oid);
$c1->remove($arr);

?>


MongoCode
http://php.net/manual/zh/class.mongocode.php



MongoDate
http://php.net/manual/zh/class.mongodate.php

简介:获得Mongo式的时间

类摘要:

MongoDate {
/* Fields */
public int $sec ;
public int $usec ;
/* 方法 */
public __construct ([ int $sec = time() [, int $usec = 0 ]] )//创建一个新的日期。
public string toDateTime ( void )//Returns a DateTime object representing this date
public string __toString ( void )//返回该日期的字符串形式的表达
}
使用:

<?php

// save a date to the database
$collection->save(array("ts" => new MongoDate()));

$start = new MongoDate(strtotime("2010-01-15 00:00:00"));
$end = new MongoDate(strtotime("2010-01-30 00:00:00"));

// find dates between 1/15/2010 and 1/30/2010
$collection->find(array("ts" => array('$gt' => $start, '$lte' => $end)));

?>


MongoRegex
http://php.net/manual/zh/class.mongoregex.php

简介:获得一个Mongo式的正则

类摘要:

MongoRegex {
/* 字段 */
public string $regex ;
public string $flags ;
/**
/pattern/flags
Mongo 能够识别六种正则表达式标记(flag):

i:大小写不敏感
m:多行
x:能够包含注释
l:语言环境
s:dotall,"." 匹配任何字符,包括换行符。
u:匹配 Unicode
*/
/* 方法 */
public __construct ( string $regex )//创建一个新的正则表达式 
public string __toString ( void )//正则表达式的字符串表达形式
}


MongoInt32
http://php.net/manual/zh/class.mongoint32.php

简介:获得一个Mongo式的integer32



MongoInt64
http://php.net/manual/zh/class.mongoint64.php

简介:获得一个Mongo式的integer64



MongoTimestamp
http://php.net/manual/zh/class.mongotimestamp.php



MongoMinKey
http://php.net/manual/zh/class.mongominkey.php



MongoMaxKey
http://php.net/manual/zh/class.mongomaxkey.php



MongoDBRef

http://php.net/manual/zh/class.mongodbref.php

这个类可以用于创建不同集合中对象间的轻量级的链接。

Motivation:如果我们需要引用其他集合中的文档。最简单的方法是在当前文档中创建一个字段。比如,有 "people" 集合和 "addresses" 集合,我们需要“关联”每个 person 和对应的 address ,可以:

Example #1 链接文档

<?php

$people = $db->people;
$addresses = $db->addresses;

$myAddress = array("line 1" => "123 Main Street", 
    "line 2" => null,
    "city" => "Springfield",
    "state" => "Vermont",
    "country" => "USA");

// save the address 保存address文档
$addresses->insert($myAddress);

// save a person with a reference to the address 保存一个people,关联刚才的address
$me = array("name" => "Fred", "address" => $myAddress['_id']);
$people->insert($me);

?>

然后,我们可以:把保存在 "people" 集合中的 MongoId 作为条件,查询 "address" 集合,来获取一个人的地址。

如果我们现在有更加一般性的的情况,我们不知道哪个集合(甚至数据库)中包含我们要引用的文档。 MongoDBRef 就是个好选择,它是一个更加通用的格式,所有的驱动和数据库都可以处理它。

如果每个“人”有一系列关联到其他多个集合的信息,例如爱好、运动、书籍等,我们可以用数个 MongoDBRef 对象来跟踪每一个 爱好 来自哪个集合:

Example #2 Creating MongoDBRef links
<?php

$people = $db->selectCollection("people");

// model trains are in the "hobbies" collection
$trainRef = MongoDBRef::create("hobbies", $modelTrains['_id']);
// soccer is in the "sports" collection
$soccerRef = MongoDBRef::create("sports", $soccer['_id']);

// now we'll know what collections the items in the "likes" array came from when
// we retrieve this document
//  # 现在当我们读取这个文档的时候,就可以知道“likes”字段里的数组元素分别来自哪个集合了。
$people->insert(array("name" => "Fred", "likes" => array($trainRef, $soccerRef)));

?>

数据库引用可以被理解为超链接:它们指定了一个文档的唯一地址,但不会自动读取或者跟踪引用、链接。、

一个数据库引用仅仅是一个普通关联数组,不是 MongoDBRef 的实例,所以这个类与其他数据类型有些不同。这个类只包含静态方法,用来操作引用。 译注:上面两段的意思概括为 

1.一个数据库引用与超链接相似,复制、删除、修改等操作不会影响原来的文档。 

2.读取这个引用可以得知指向的文档的位置,但不能知道文档的内容,要手动解引用。 

3.这个“引用”保存到Mongo的时候就是普通数组

MongoDBRef {
/* 方法 */
public static array create ( string $collection , mixed $id [, string $database ] )//创建一个新的数据库引用
public static array get ( MongoDB $db , array $ref )//获取引用所指向的对象
public static bool isRef ( mixed $ref )//检测数组是否为数据库引用
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值