comedy; // 选择comedy数据库,如果以前没该数据库会自动创建,也可以用$m->selectDB("comedy");$collection = $db->collection; //选择comedy里面的collection集合,相当于RDBMS里面的表,也-可以使用$db->selectCollection("collection");/*********添加一个元素**************/$obj = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );$collection->insert($obj); //将$obj 添加到$collection 集合中/*********添加另一个元素**************/$obj = array( "title" => "XKCD", "online" => true );$collection->insert($obj);$cursor = $collection->find();foreach ($cursor as $obj) { //遍历所有集合中的文档echo $obj["title"] . "\n";}$m->close(); //断开MongoDB连接
$query = array( "i" => 71 );
$cursor = $collection->find( $query ); // 在$collectio集合中查找满足$query的文档while( $cursor->hasNext() ) {
var_dump( $cursor->getNext() );}$collection -> findOne(); //返回$collection集合中第一个文档
$collection -> count(); //返回$collection集合中文档的数量
$coll->ensureIndex( array( "i" => 1 ) ); // 为i “这一列”加索引 降序排列$coll->ensureIndex( array( "i" => -1, "j" => 1 ) ); // 为i “这一列”加索引 降序排列 j升序查询时,每个Object插入时都会自动生成一个独特的_id,它相当于RDBMS中的主键,用于查询时非常方便
如:<?php
$person = array("name" => "joe");
$people->insert($person);
$joe = $people->findOne(array("_id" => $person['_id']));
?>
更新时:
假如我们想修改下面文档中comments中author的名字{
"_id" : ObjectId("4b06c282edb87a281e09dad9"), "content" : "this is a blog post.", "comments" : [ { "author" : "Mike", "comment" : "I think that blah blah blah...", }, { "author" : "John", "comment" : "I disagree." } ]}为了改变内部的一个域, 我们用 $set (保证文档中其他域不被移除)并且comment的索引也变化
<?php
$collection->update($criteria, array('$set' => array("comments.1" => array("author" => "Jim")))); //$criteria 为要更新的元素
?>
删除一个数据库
$m -> dropDB("comedy");
列出所有可用数据库
$m->listDBs(); //无返回值