<?php header("Content-type: text/html; charset=utf-8"); //$mo = new Mongo(); //var_dump($mo); //$dbs = $mo->listDBs(); //var_dump($dbs); //创建一个数据库的意思,也就是创建一个MongoDB对像 //$db = new MongoDB($mo,’username’); //$db = $mo->username; $mo = new Mongo(); $db = $mo->comedy; $collection = $db->collection; //添加一个元素 //$obj = array("title"=>"这是标题", "author"=>"作者向晓东"); //$collection->insert($obj); //添加另外一个元素 //$obj = array("title"=>"XKCD", "online"=>true); //$collection->insert($obj); $cursor = $collection->find(); var_dump($cursor); foreach($cursor as $obj){ echo $obj['title']."<BR><BR>"; if(isset($obj['author'])){ echo $obj['author']."<BR><BR>"; } if(isset($obj['online'])){ echo $obj['online']."<BR><BR>"; } } //$mo->close(); //关闭链接 echo "<h1>查询</h1>"; //查询 $query = array("title"=>"XKCD"); $cursor = $collection->find($query); //while($cursor->hasNext()){ //var_dump($cursor->getNext); //} foreach ($cursor as $key => $value) { //var_dump($value); echo $value['title']."<BR><BR>"; } //返回$collection集合中第一个文档 $one = $collection->findOne(); var_dump($one); echo "<BR><BR>"; $count = $collection->count(); echo $count; echo "<BR><BR>"; //没有测试过 //$coll->ensureIndex( array( "i" => 1 ) ); // 为i “这一列”加索引 降序排列 //$coll->ensureIndex( array( "i" => -1, "j" => 1 ) ); // 为i “这一列”加索引 降序排列 j升序 //$collection->ensureIndex(array("title"=>-1)); //不管用 $cursor = $collection->find(); //$cursor->ensureIndex(array("title"=>1)); foreach ($cursor as $key => $value) { //var_dump($value); echo $value['title']."<BR><BR>"; } $person = array("title" => "xxdxxd", "author"=>"author"); $collection->insert($person); echo "插入数据的ID".$person['_id']."<BR><BR>"; $joe = $collection->findOne(array("_id" => $person['_id'])); var_dump($joe); ?>