更新資料

在 MongoDB 的資料更新方法有兩種,一種是更新 document 中部份的資訊,假設 documents 的資料是這樣:

{
  "firstName" : "G.T.",
  "lastName" : "Wang",
  "roles" : [  "developer",  "webmaster" ]
}

更新 email 的資訊:

$cDemo->update(
  array("firstName" => "G.T.", "lastName" => "Wang"),
  array('$set' => array("email" => "gtw@gtwang.org"))
);

更新之後,會變成這樣:

{
  "firstName" : "G.T.",
  "lastName" : "Wang",
  "roles" : [  "developer",  "webmaster" ],
  "email" : "gtw@gtwang.org"
}

另外一種更新方式是將整筆 document 覆蓋過去,假設 documents 的資料是這樣:

{
  "firstName" : "G.T.",
  "lastName" : "Wang",
  "roles" : [  "developer",  "webmaster" ]
}

使用新的 document 直接蓋掉舊的:

$cDemo->update(
  array("firstName" => "G.T.", "lastName" => "Wang"),
  array(
    "username" => "gtwang",
    "info" => array("name" => "G. T. Wang", "email" => "gtw@gtwang.org"),
    "likes" => array()
  )
);

更新之後,會變成這樣:

{
  "username" : "gtwang",
  "info" : { "name" : "G. T. Wang", "email" : "gtw@gtwang.org" },
  "likes" : [ ]
}

其他進階的範例請參考 update 的網頁說明文件。

刪除資料

假設我們想要刪除這一筆資料:

{
  "_id" : ObjectId("5650f638b2fd7f7b198b4567"),
  "firstName" : "G.T.",
  "lastName" : "Wang",
  "roles" : [  "developer",  "webmaster" ]
}

可以依據 _id 刪除:

$id = '5650f638b2fd7f7b198b4567';
$cDemo->remove(array('_id' => new MongoId($id)));

或是使一般的查詢條件來找出這一筆 document 並刪除:

$cDemo->remove(
  array("firstName" => "G.T.", "lastName" => "Wang")
);

假設資料庫中有很多筆重複的資料時:

{ "_id" : ObjectId("5650fb61b2fd7fd91b8b4567"), "firstName" : "G.T.", "lastName" : "Wang", "roles" : [  "developer",  "webmaster" ] }
{ "_id" : ObjectId("5650fb92b2fd7fec1b8b4567"), "firstName" : "G.T.", "lastName" : "Wang", "roles" : [  "developer",  "webmaster" ] }
{ "_id" : ObjectId("5650fb93b2fd7fee1b8b4567"), "firstName" : "G.T.", "lastName" : "Wang", "roles" : [  "developer",  "webmaster" ] }
{ "_id" : ObjectId("5650fb94b2fd7ff01b8b4567"), "firstName" : "G.T.", "lastName" : "Wang", "roles" : [  "developer",  "webmaster" ] }

我們可以利用這樣的方式把重複的資料刪掉,只留下一筆:

$condition = array("firstName" => "G.T.", "lastName" => "Wang");

// 計算重複資料筆數
$remaining = $cDemo->count($condition);

// 要刪除的資料筆數
$delete = $remaining - 1;

// 刪除資料
while ($delete > 0) {
  $cDemo->remove($condition, array("justOne" => true));
  $delete--;
}

執行完之後,就只會剩下一筆:

{ "_id" : ObjectId("5650fb94b2fd7ff01b8b4567"), "firstName" : "G.T.", "lastName" : "Wang", "roles" : [  "developer",  "webmaster" ] }