PHP官方手册翻译-MongoDB教程

介绍

针对MongoDB的云计算PHP驱动

快速上手连接,插入,查询,遍历结果,断开连接,下面的教程每一节都有详细介绍


<?php

// 连接
$m = new Mongo();

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

// 选择一个集合 (类似一个关系数据库的表)
$collection $db->cartoons;

// 添加一条记录
$obj = array( "title" => "Calvin and Hobbes""author" => "Bill Watterson" );
$collection->insert($obj);

// 添加另一个不同"形状"的记录
$obj = array( "title" => "XKCD""online" => true );
$collection->insert($obj);

// 从集合中查询所有记录
$cursor $collection->find();

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

?>

将输出:

Calvin and Hobbes
XKCD

建立一个连接

连接一个数据库服务使用下面的一个:

<?php

$connection 
= new Mongo(); // 连接localhost:27017
$connection = new Mongo"example.com" ); // 连接远程主机 (默认端口: 27017)
$connection = new Mongo"example.com:65432" ); // 连接指定端口的远程主机

?> 

不需要明确的断开连接.当$connection对象超出范围,会自动关闭并释放一些资源.

参考

The chapter on connecting covers different types of connections.

The API documentation on the Mongo class and Mongo::__construct() give a comprehensive look at all possible options with a number of examples. 


获取数据库

要选择使用的数据库,使用:

 

<?php

$db 
$connection->dbname;

?>

事先不需要创建数据库,通过你选的就会创建新库.

注意别打错字,否则会不小心创建新的库,导致误导性错误.

<?php

$db 
$connection->mybiglongdbname;
// 随便写个
$db $connection->mybiglongdbanme;
// 敲错一个就创建了一个不同的连接

?>

参考

The API documentation on the MongoDB class contains more information about database objects.

Getting A Collection

Getting a collection has the same syntax as getting a database:

<?php

$db 
$connection->baz;
$collection $db->foobar;

// or, more succinctly
$collection $connection->baz->foobar;

?>

A collection is analogous to a table (if you are familiar with relational databases).

See Also

The API documentation on the MongoCollection class contains more information about collection objects.

Inserting a Document

Associative arrays are the basic object that can be saved to a collection in the database. A somewhat random "document" might be:

<?php

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

?>

Note that you can have nested arrays and objects.

To insert this document, use MongoCollection::insert():

<?php

$collection
->insert$doc );

?>

See Also

The API documentation on MongoCollection::insert() contains more information about inserting data.

Finding Documents using MongoCollection::findOne()

To show that the document we inserted in the previous step is there, we can do a simple MongoCollection::findOne() operation to get a single document from the collection. This method is useful when there only is one document matching the query or you are only interested in one result.

<?php

$obj 
$collection->findOne();
var_dump$obj );

?>

This should print:

array(6) {
  ["_id"]=>
  object(MongoId)#8 (1) {
    ["$id"]=>
    string(24) "4e2995576803fab768000000"
  }
  ["name"]=>
  string(7) "MongoDB"
  ["type"]=>
  string(8) "database"
  ["count"]=>
  int(1)
  ["info"]=>
  array(2) {
    ["x"]=>
    int(203)
    ["y"]=>
    int(102)
  }
  ["versions"]=>
  array(3) {
    [0]=>
    string(5) "0.9.7"
    [1]=>
    string(5) "0.9.8"
    [2]=>
    string(5) "0.9.9"
  }
}

Note that there is an _id field that has been added automatically to your document. _id is the "primary key" field. If your document does not specify one, the driver will add one automatically.

If you specify your own _id field, it must be unique to the collection. See the example here:

<?php

$db
->foo->insert(array("_id" => 1), array("safe" => true));
// this will throw an exception
$db->foo->insert(array("_id" => 1), array("safe" => true));

// this is fine, as it is a different collection
$db->bar->insert(array("_id" => 1), array("safe" => true));

?>

Note that these inserts pass a second array: array("safe" => true). This second field specifies options for the insert. By default, the driver does not wait for a database response for writes, so the driver would not catch the the _id. As we specify that this is a "safe" write, the driver will wait for a database response and see that the write did not go through. In general, all writes should use the "safe" option (it is omitted in previous examples for simplicity).

See Also

MongoCollection::findOne() for more information about finding data.

MongoId goes into more detail on unique ids.

The writes section covers safe writes in more depth, as do the writing functions such as MongoCollection::insert(), MongoCollection::update(), and MongoCollection::remove().

Adding Multiple Documents

In order to do more interesting things with queries, let's add multiple simple documents to the collection. These documents will just be of the form array( "i" => value ); and we can do this fairly efficiently in a loop:

<?php

for($i=0$i<100$i++) {
    
$collection->insert( array( "i" => $i ) );
}

?>

Notice that we can insert arrays with different key sets into the same collection. This aspect is what we mean when we say that MongoDB is "schema-free".

Counting Documents in A Collection

Now that we've inserted 101 documents (the 100 we did in the loop, plus the first one), we can check to see if we have them all using the MongoCollection::count() method.

<?php

echo $collection->count();

?>
and it should print 101.

Using a Cursor to Get All of the Documents

In order to get all the documents in the collection, we will use MongoCollection::find(). The find() method returns a MongoCursor object which allows us to iterate over the set of documents that matched our query. So to query all of the documents and print them out:

<?php

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

?>
and that should print all 101 documents in the collection. $id is the _id field of a document (cast to a string) and $value is the document itself.

See Also

The API documentation on MongoCollection::find() contains more information about finding data.

Setting Criteria for a Query

We can create a query to pass to the MongoCollection::find() method to get a subset of the documents in our collection. For example, if we wanted to find the document for which the value of the "i" field is 71, we would do the following:

<?php

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

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

?>

and it should just print just one document:

array(2) {
  ["_id"]=>
  object(MongoId)#6 (0) {
  }
  ["i"]=>
  int(71)
  ["_ns"]=>
  "testCollection"
}

Getting A Set of Documents With a Query

We can use the query to get a set of documents from our collection. For example, if we wanted to get all documents where "i" > 50, we could write:

<?php

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

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

?>

which should print the documents where i > 50. We could also get a range, say 20 < i <= 30:

<?php

$query 
= array( "i" => array( "\$gt" => 20"\$lte" => 30 ) );
$cursor $coll->find$query );

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

?>

Remember to always escape the $-symbol or use single quotes. Otherwise PHP will interpret it to be the variable $gt.

Creating An Index

MongoDB supports indexes, and they are very easy to add on a collection. To create an index, you specify the field name and direction: ascending (1) or descending (-1). The following creates an ascending index on the "i" field:

<?php

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

?>

Indexing is critical for good read performance as your data grows. If you are not familiar with indexing, check out the MongoCollection::ensureIndex() documentation and the core » MongoDB indexing documentation


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值