/** * {@inheritdoc} */ public function connect(array $config) { $requiredParams = array('hostname', 'db', 'collection'); foreach ($requiredParams as $param) { if (!isset($config[$param])) { throw new SetupException('Missing config attribute "' . $param . '"'); } } $port = isset($config['port']) ? (int) $config['port'] : 27017; $mongo = new \Mongo('mongodb://' . $config['hostname'] . ':' . $port); $this->adapter = $mongo->selectDB($config['db']); $this->collection = $this->adapter->selectCollection($config['collection']); return $this; }
/** * 构造查询 * * @param Mongo $mongo MongoDB连接 * @param string $db 数据库 * @param string $collection 集合 */ function __construct(Mongo $mongo, $db, $collection) { $this->_dbName = $db; $this->_collectionName = $collection; $this->_db = $mongo->selectDB($this->_dbName); $this->_collection = $mongo->selectCollection($this->_dbName, $this->_collectionName); }
public function testBasic() { $r1 = new MongoRegex("//"); $this->assertEquals($r1->regex, ""); $this->assertEquals($r1->flags, ""); $r2 = new MongoRegex("/foo/bar"); $this->assertEquals($r2->regex, "foo"); $this->assertEquals($r2->flags, "bar"); $r3 = new MongoRegex($r2); $this->assertEquals($r3->regex, "foo"); $this->assertEquals($r3->flags, "bar"); $stupid_str = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"; $rstupid = new MongoRegex("/{$stupid_str}/flagflagflagflagflag"); $this->assertEquals($rstupid->regex, $stupid_str); $this->assertEquals($rstupid->flags, "flagflagflagflagflag"); $m = new Mongo(); $c = $m->selectCollection('phpunit', 'regex'); $c->drop(); $c->insert(array('x' => 0, 'r1' => $r1)); $c->insert(array('x' => 1, 'r2' => $r2)); $c->insert(array('x' => 2, 'stupid' => $rstupid)); $obj = $c->findOne(array('x' => 0)); $this->assertEquals($obj['r1']->regex, ""); $this->assertEquals($obj['r1']->flags, ""); $obj = $c->findOne(array('x' => 1)); $this->assertEquals($obj['r2']->regex, "foo"); $this->assertEquals($obj['r2']->flags, "bar"); $obj = $c->findOne(array('x' => 2)); $this->assertEquals($obj['stupid']->regex, $stupid_str); $this->assertEquals($obj['stupid']->flags, "flagflagflagflagflag"); }
/** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. * * @access protected */ protected function setUp() { $m = new Mongo(); $this->object = $m->selectCollection('phpunit', 'c'); $this->object->drop(); // $this->object->start = memory_get_usage(true); }
/** * Return a "MongoCollection" instance. * * @return \MongoCollection */ private function getCollection() { if (null === $this->collection) { $this->collection = $this->mongo->selectCollection($this->options['database'], $this->options['collection']); } return $this->collection; }
/** * Init 初始化 * @param string $db * @param string $collection */ public static function init($db = '', $collection = '') { if (!self::$_mongoDB) { $config = self::$_config; $conStr = "mongodb://"; if ($config['user'] && $config['password']) { $conStr .= "{$config['user']}:{$config['password']}@"; } $conStr .= "{$config['host']}:{$config['port']}"; $_mongoDB = new Mongo($conStr, array("connect" => false)); if ($db && $collection) { self::$_mongoDB = $_mongoDB->selectCollection($db, $collection); } else { self::$_mongoDB = $_mongoDB->selectCollection(static::$_db, static::$_collection); } } }
/** * Internal convenience method that returns the instance of the MongoDB Collection * * @return \MongoCollection */ protected function getMongo() { if ($this->mongo === null) { $mongo = new \Mongo($this->dsn); list($database, $collection, ) = explode('/', substr(parse_url($this->dsn, PHP_URL_PATH), 1)); $this->mongo = $mongo->selectCollection($database, $collection); } return $this->mongo; }
function setup() { if (PHP_INT_SIZE != 4) { $this->markTestSkipped("Only for 32 bit platforms"); } ini_set('mongo.native_long', 0); ini_set('mongo.long_as_object', 0); $m = new Mongo(); $this->object = $m->selectCollection("phpunit", "ints"); $this->object->drop(); }
public function testDropDB() { $this->object->connect(); $c = $this->object->selectCollection("temp", "foo"); $c->insert(array('x' => 1)); $this->object->dropDB("temp"); $this->assertEquals($c->findOne(), NULL); $db = $this->object->selectDB("temp"); $c->insert(array('x' => 1)); $this->object->dropDB($db); $this->assertEquals($c->findOne(), NULL); }
function insertarTweetInfo($id_tweet, $tweet, $rts, $favs, $fecha_creacion, $usuario, $url_imagen, $followers, $following, $num_tweets) { //creamos la conexion con la BD $mongo = new Mongo(); $db = $mongo->selectDB("TwettsDB"); $c_twettsMovilidad = $mongo->selectCollection("TwettsDB", "twettsMovilidad"); $nuevoTweet = array("ID" => $id_tweet, "TWETT" => $tweet, "RETWETTS" => $rts, "FAVORITOS" => $favs, "FECHA_CREACION" => $fecha_creacion, "USUARIO" => $usuario, "URL_IMAGEN" => $url_imagen, "N_MIS_SEGUIDORES" => $followers, "N_SEGUIDORES" => $following, "N_TWETTS_ENVIADOS" => $num_tweets); $c_twettsMovilidad->insert($nuevoTweet); $twettsMovilidad = $c_twettsMovilidad->find(); foreach ($twettsMovilidad as $twett) { print_r($twett); } }
public function testGetDBRef() { $c = $this->object->selectCollection('foo'); $c->drop(); for ($i = 0; $i < 50; $i++) { $c->insert((object) array('x' => rand()), array("safe" => true)); } $obj = $c->findOne(); $ref = $this->object->createDBRef('foo', $obj); $obj2 = $this->object->getDBRef($ref); $this->assertNotNull($obj2); $this->assertEquals($obj['x'], $obj2['x']); }
public function testConstruct() { $m = new Mongo("localhost:27017,localhost:27018", false); $m->pairConnect(); $c = $m->selectCollection("phpunit", "test"); $c->insert(array("foo", "bar")); $left = new Mongo("localhost:27017"); $left->selectCollection("foo", "bar")->insert(array('x' => 1)); $lerr = $left->lastError(); $right = new Mongo("localhost:27018"); $right->selectCollection("foo", "bar")->insert(array('x' => 1)); $rerr = $right->lastError(); }
/** * Initializes this logger. * * @throws sfInitializationException * * @param sfEventDispatcher $dispatcher A sfEventDispatcher instance * @param array $options An array of options. * * @return bool */ public function initialize(sfEventDispatcher $dispatcher, $options = array()) { if (!class_exists('Mongo')) { throw new sfInitializationException('The MongoDB extension is not installed or enabled.'); } foreach ($this->getRequiredOptions() as $eachOption) { if (!isset($options[$eachOption])) { throw new sfInitializationException(sprintf('The required option "%s" is missing.', $eachOption)); } } $this->options = array_merge($this->getDefaultOptions(), $options); if ($this->options['username'] and $this->options['password']) { $this->handler = new Mongo(sprintf('mongodb://%s:%s@%s:%d/%s', $this->options['username'], $this->options['password'], $this->options['host'], $this->options['port'], $this->options['database'])); } else { $this->handler = new Mongo(sprintf('mongodb://%s:%d', $this->options['host'], $this->options['port'])); } if (!empty($this->options['create'])) { $this->handler->selectDB($this->options['database'])->createCollection($this->options['collection'], $this->options['create']['capped'], $this->options['create']['size'], $this->options['create']['max']); } $this->collection = $this->handler->selectCollection($this->options['database'], $this->options['collection']); return parent::initialize($dispatcher, $this->options); }
public function testMethods() { $m = new Mongo(); $c = $m->selectCollection('phpunit', 'objs4'); $c->drop(); $f = new Foo(); $c->insert($f); $f->x = 3; $c->save($f); $f->y = 7; $c->update(array('_id' => $f->_id), $f); $c->remove($f); }
/** * Internal convenience method that returns the instance of the MongoDB Collection * * @return \MongoCollection */ protected function getMongo() { if ($this->mongo === null) { if (preg_match('#^(mongodb://.*)/(.*)/(.*)$#', $this->dsn, $matches)) { $mongo = new \Mongo($matches[1] . (!empty($matches[2]) ? '/' . $matches[2] : '')); $database = $matches[2]; $collection = $matches[3]; $this->mongo = $mongo->selectCollection($database, $collection); } else { throw new \RuntimeException(sprintf('Please check your configuration. You are trying to use MongoDB with an invalid dsn "%s". The expected format is "mongodb://*****:*****@location/database/collection"', $this->dsn)); } } return $this->mongo; }
public function testDropDB() { $this->object->connect(); $c = $this->object->selectCollection("temp", "foo"); $result = $c->db->command(array("ismaster" => 1)); if (!$result['ismaster']) { $this->markTestSkipped("can't test writes on slave"); return; } $c->insert(array('x' => 1)); $this->object->dropDB("temp"); $this->assertEquals($c->findOne(), NULL); $db = $this->object->selectDB("temp"); $c->insert(array('x' => 1)); $this->object->dropDB($db); $this->assertEquals($c->findOne(), NULL); }
public function testBasic() { if (preg_match("/5\\.1\\../", phpversion())) { $this->markTestSkipped("No implicit __toString in 5.1"); return; } $id1 = new MongoId(); $this->assertEquals(strlen("{$id1}"), 24); $copy = new MongoId($id1); $this->assertEquals((string) $id1, (string) $copy); $id2 = new MongoId('49c10bb63eba810c0c3fc158'); $this->assertEquals((string) $id2, '49c10bb63eba810c0c3fc158'); $m = new Mongo(); $c = $m->selectCollection("phpunit", "id"); $c->drop(); $c->insert(array("_id" => 1)); $obj = $c->findOne(); $this->assertEquals($obj['_id'], 1); }
public function add_forecast() { $api = new \models\ApiModel(); $towns = $api->getCities(); $config = \config\Config::getInstance(); $db = new \Mongo("mongodb://" . $config['db_host'] . ":" . $config['db_port'] . "/" . $config['db_database']); $collection = $db->selectCollection('ngs', 'forecasts'); foreach ($towns as $town) { $decoded = $api->getForecast($town['name']); foreach ($decoded['forecasts'] as $forecasts) { foreach ($forecasts['hours'] as $hours) { if ($hours['hour'] == '12') { $mas = array('temperature' => $hours['temperature']['avg'], 'pressure' => $hours['pressure']['avg'], 'humidity' => $hours['humidity']['avg'], 'wind' => array('speed' => $hours['wind']['speed']['avg'], 'direction' => $hours['wind']['direction']['title']), 'cloud' => $hours['cloud']['title'], 'precipitation' => $hours['precipitation']['title']); } } $document = array('date' => new \MongoDate(strtotime($forecasts['date'])), 'city' => $town['name'], 'forecast' => $mas); $collection->update(array('city' => $document['city'], 'date' => $document['date']), array('$set' => $document), array('upsert' => true)); } } }
<?php $config = array('method' => 'bulk_insert', 'insertCounts' => array()); for ($i = 7000000; $i <= 10000000; $i += 1000000) { $config['insertCounts'][] = $i; } $m = new Mongo(); $c = $m->selectCollection('test', 'benchmark'); foreach ($config['insertCounts'] as $docCount) { // Re-create the database for each attempt $c->drop(); // echo sprintf("-> %s %d docs:\n", $config['method'], $docCount); switch ($config['method']) { case 'bulk_insert': $insertStart = microtime(true); $docsWritten = 0; while ($docsWritten < $docCount) { $insertAtOnce = $docCount - $docsWritten > 1000 ? 1000 : $docCount - $docsWritten; $docs = array(); for ($i = 0; $i < $insertAtOnce; $i++) { $docs[] = array('_id' => new MongoId(), 'foo' => 'bar'); } $c->batchInsert($docs); $docsWritten = $docsWritten + $insertAtOnce; } $c->findOne(); $insertEnd = microtime(true); break; case 'single_insert': $insertStart = microtime(true); for ($i = 0; $i < $docCount; $i++) {
protected function setUp() { $m = new Mongo(); $this->object = $m->selectCollection("phpunit", "bindata"); $this->object->drop(); }
/** * Internal convenience method that returns the instance of the MongoDB Collection * * @return \MongoCollection */ protected function getMongo() { if ($this->mongo === null) { if (preg_match('#^(mongodb://.*)/(.*)/(.*)$#', $this->dsn, $matches)) { $mongo = new \Mongo($matches[1]); $database = $matches[2]; $collection = $matches[3]; $this->mongo = $mongo->selectCollection($database, $collection); } else { throw new \RuntimeException('Please check your configuration. You are trying to use MongoDB with an invalid dsn. "'.$this->dsn.'"'); } } return $this->mongo; }
public function testEnsureIndex() { $mongoConnection = new Mongo('127.0.0.1:27017'); $collection = $mongoConnection->selectCollection("debug", "col1"); $data = array("field" => "some data", "date" => date("Y-m-s")); $this->assertEquals(true, $collection->save($data)); $tmp = array("date" => 1); $this->assertEquals(1, $tmp['date']); $this->assertEquals(true, $collection->ensureIndex($tmp)); $this->assertEquals(1, $tmp['date']); }
public function testCursorCount() { $m = new Mongo(); $c = $m->selectCollection("phpunit", "bar"); $c->insert(array("foo" => "bar")); $c->insert(array("foo" => "bar")); $mem = memory_get_usage(true); for ($i = 0; $i < 10000; $i++) { $c->find()->count(); } $this->assertEquals($mem, memory_get_usage(true)); }
/** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. * * @access protected */ public function setUp() { $m = new Mongo(); $this->object = $m->selectCollection('foo', 'bar'); $this->object->drop(); }
public function get_connection($type) { try { $connection_string = $this->_build_connection_string(); if (class_exists('\\MongoClient')) { $m = new \MongoClient($connection_string); } else { $m = new \Mongo($connection_string); } return $m->selectCollection($this->inform('mongo:db'), $type); // XXX Conf should be taken from configurator object } catch (\MongoConnectionException $e) { $this->report_error("Failed to connect to MongoDB, message is: " . $e->getMessage()); throw $this->except($e->getMessage(), 'connection_failure'); } catch (\Exception $e) { $this->report_error("Failed to connect to database or collection, message is: " . $e->getMessage()); throw $this->except($e->getMessage(), 'db_failure'); } }
public function setUp() { $m = new Mongo(); $this->object = $m->selectCollection("phpunit", "minmax"); $this->object->drop(); }
<?php $mongoCliente = new MongoClient(""); $mongo = new Mongo('127.0.0.1:27017'); $mongo->selectDB("anotation"); $mongo->selectCollection($mongo, "usuario"); $mongo->find(array());
public function testEnsureIndex() { setTimezone(); $mongoConnection = new Mongo('127.0.0.1:27017'); $collection = $mongoConnection->selectCollection("debug", "col1"); $data = array("field"=>"some data","date"=>date("Y-m-s")); $result = $collection->save($data, array("safe" => true)); $this->assertEquals(1, $result["ok"], json_encode($result)); $tmp = array("date" => 1); $this->assertEquals(1, $tmp['date']); $this->assertEquals(true, $collection->ensureIndex($tmp)); $this->assertEquals(1, $tmp['date']); unsetTimezone(); }
/** *. * @param Mongo instance $mongo */ public function setMongo(\Mongo $mongo, $database, $collection) { $this->collection = $mongo->selectCollection($database, $collection); }
/** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. * * @access protected */ protected function setUp() { $m = new Mongo(); $this->object = $m->selectCollection('phpunit', 'c'); $this->object->drop(); }