Mongodb之(小試牛刀)

來源:互聯網
上載者:User

今天外面刮著呼呼的大風,能在一個溫暖的小屋寫著部落格也是北漂的一種幸福。好了廢話不多說,今天主要說一下php串連、操作mongodb,如果你沒有看上兩期的內容,不知道如何安裝php對mongodb的擴充的話請您返回去看《Mongodb之(初識如故)》和《Mongodb之(初出茅廬)》   。

php 串連mongodb

try {      $mongo = new Mongo("mongodb://username:password@127.0.0.1:27017/db1");}catch(MongoConnectionException $e) {        print $e->getMessage();        exit;}        

選擇資料庫blog

$db = $mongo->blog;

關閉資料庫

$conn->close();

 

選擇操作集合

$collection = $db->users;

插入資料

$user = array('name' => 'caleng', 'city' => 'beijing');$collection->insert($user);

修改資料

$newdata = array('$set' => array("city" => "shanghai"));$collection->update(array("name" => "caleng"), $newdata);

刪除資料

$collection->remove(array('name'=>'caleng'), array("justOne" => true));

尋找資料

尋找一條資料

$result= $collection->findone(array("name"=>"caleng"));

查詢一個列表

//找出建立時間大於某一時間的資料$start = 1;$counditionarray=array("ctime"=>array('$gt'=>1337184000));$list_data = $this->game_handle->find($counditionarray);$total = $this->game_handle->count($counditionarray);$list_data->limit($count); //資料結束位置$list_data->skip($start);  //資料開始取的位置var_dump($list_data);

 in查詢

$cursor = $collection->find(array(    'name' => array('$in' => array('Joe', 'Wendy'))));

group查詢

$collection->insert(array("category" => "fruit", "name" => "apple"));$collection->insert(array("category" => "fruit", "name" => "peach"));$collection->insert(array("category" => "fruit", "name" => "banana"));$collection->insert(array("category" => "veggie", "name" => "corn"));$collection->insert(array("category" => "veggie", "name" => "broccoli"));$keys = array("category" => 1);$initial = array("items" => array());$reduce = "function (obj, prev) { prev.items.push(obj.name); }";$g = $collection->group($keys, $initial, $reduce);echo json_encode($g['retval']);

輸出結果:

[{"category":"fruit","items":["apple","peach","banana"]},{"category":"veggie","items":["corn","broccoli"]}]

可以看出得到的結果是一個二維 數組

array(    0 => array("category" =>"fruit", "items"=>array("apple","peach","banana")),    1 => array("category" =>"veggie", "items"=>array("corn","broccoli")))

在這裡這寫了一些簡單的操作,如果您想用php更好的作用mongodb 那就看手冊吧。

地址發來:http://cn2.php.net/manual/zh/class.mongocollection.php

好了,Mongodb就寫到這裡了。 我想大家在後面的使用中越來越輕車熟路的。
借用 張雨生的《我期待》跟大家 " say goodbye      say goodbye ye a  昂首闊步不留一絲遺憾!"

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.