Skip to content

Instantly share code, notes, and snippets.

@ishtaka
Last active December 17, 2015 01:39
Show Gist options
  • Save ishtaka/5530190 to your computer and use it in GitHub Desktop.
Save ishtaka/5530190 to your computer and use it in GitHub Desktop.
[PHP]mongoDBをPHPから使うサンプル
<?php
// connect
$mongo = new MongoClient("localhost:27017");
$db = $mongo->selectDB("test");
$col = $db->createCollection("test");
// insert
$db = $mongo->selectDB('test');
$col = $db->selectCollection('test');
$data = array("name" => "foo", "num" => array('a' => 1, 'b' => 12));
$col->insert($data);
// select
$cursor = $col->find(array('name' => 'foo'));
foreach ($cursor as $key => $val) {
var_dump($val);
}
array(3) {
["_id"]=>
object(MongoId)#7 (1) {
["$id"]=>
string(24) "5187ee61837246a905000000"
}
["name"]=>
string(3) "foo"
["num"]=>
array(2) {
["a"]=>
int(1)
["b"]=>
int(12)
}
}
// update
$db = $mongo->selectDB('test');
$col = $db->selectCollection('test');
$cursor = $col->findOne(array('num.a' => 1));
$id = $cursor['_id'];
$col->update(array('_id' => $id), array('$set' => array( 'num' => array('a' => 'up-ok'))));
array(3) {
["_id"]=>
object(MongoId)#8 (1) {
["$id"]=>
string(24) "5187ee61837246a905000000"
}
["name"]=>
string(3) "foo"
["num"]=>
array(1) { // 上書きされるので、{"num" : {"b" : 12}}が消える
["a"]=>
string(5) "up-ok"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment