function getConnection($cache = false) { static $first; $conf = new \ActiveMongo2\Configuration(__DIR__ . "/tmp/mapper.php"); $conf->addModelPath(__DIR__ . '/docs')->development(); if (!empty($_SERVER["NAMESPACE"])) { if (!$first) { print "Using namespace {$_SERVER['NAMESPACE']}\n"; } $conf->SetNamespace($_SERVER["NAMESPACE"]); } if (!$first) { $mongo = new MongoClient(); $mongo->selectDB('activemongo2_tests')->drop(); $mongo->selectDB('activemongo2_tests_foobar')->drop(); $config = new ActiveMongo2\Configuration(); unlink($config->getLoader()); } if (empty($_SERVER["NAMESPACE"])) { $zconn = new \ActiveMongo2\Client(new MongoClient(), 'activemongo2_tests', __DIR__ . '/docs'); } else { $zconn = new \ActiveMongo2\Connection($conf, new MongoClient(), 'activemongo2_tests'); } $zconn->AddConnection('foobar', new MongoClient(), 'activemongo2_tests_foobar', 'zzzz'); if ($cache) { $zconn->setCacheStorage(new \ActiveMongo2\Cache\Storage\Memory()); } $first = true; return $zconn; }
/** * Get default database * * @return \MongoDB */ public function getDefaultDatabase() { if (is_null($this->defaultDb)) { $this->defaultDb = $this->client->selectDB($this->config['database_name']); } return $this->defaultDb; }
/** * Get the collection instance, for internal use. Only creates the MongoCollection * when called upon. * @return MongoDB */ public function getDatabase() { if (!$this->db instanceof \MongoDB) { $this->db = $this->client->selectDB($this->options['db']); } return $this->db; }
public function getDriver() { if (!$this->_driver) { if (!isset($this->_config['handler_config'])) { throw new Exception("Cannot found config for Mongo Session Handler"); } $cfg = $this->_config['handler_config']; $cfg = isset($cfg['options']) ? $cfg['options'] : array("connect" => true); if (class_exists('Mongo')) { $this->_driver = new \Mongo($cfg['dsn'], $cfg['options']); } else { if (class_exists('MongoClient')) { $this->_driver = new \MongoClient($cfg['dsn'], $cfg['options']); } } if (isset($cfg['options']['db'])) { $db = $this->_driver->selectDB($cfg['options']['db']); } else { $db = $this->_driver->selectDB('session'); } $this->_collectionName = isset($cfg['collection']) ? $cfg['collection'] : 'session_data'; $this->_collection = $db->selectCollection($this->_collectionName); } return $this->_driver; }
public function connect() { if ($this->_connection) { return; } $host = $this->_config['connection']['server']; if (isset($this->_config['connection']['username']) && isset($this->_config['connection']['password'])) { $host = $this->_config['connection']['username'] . ':' . $this->_config['connection']['password'] . '@' . $host; } if (strpos($host, 'mongodb://') !== 0) { $host = 'mongodb://' . $host; } if (!isset($options)) { $options = array(); } $options['connect'] = FALSE; $this->_connection = new MongoClient($host, $options); try { $this->_connection->connect(); } catch (MongoConnectionException $e) { throw new Exception('Unable to connect to Mongo server at :hostnames', array(':hostnames' => $e->getMessage())); } if (!isset($this->_config['connection']['db'])) { throw new Exception('No database specified in MangoDB Config'); } $this->_db = $this->_connection->selectDB($this->_config['connection']['db']); return $this->_connected = TRUE; }
/** * This function Define and assign the database */ private function setConnection() { $cn = new \MongoClient(); if (env('DB_ENV', 'development') == 'development') { $this->database = $cn->selectDB("dbDevEndaroo01"); } else { $this->database = $cn->selectDB("dbProdEndaroo01"); } }
/** * This function Define and assign the database */ private function setConnection() { $cn = new \MongoClient(); if (env('DB_ENV', 'development') == 'development') { self::$database = $cn->selectDB("dbAbbaDev01"); } else { self::$database = $cn->selectDB("dbAbbaProd01"); } }
private static function init() { if (self::$db) { return; } $config = Kohana::$config->load('database')->get('mongo'); self::$client = new MongoClient($config['host']); self::$db = self::$client->selectDB($config['database']); }
/** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $client = new \MongoClient($this->getContainer()->getParameter('mongo_server')); $oldDb = $client->selectDB("muchacuba_old"); $newDb = $client->selectDB("muchacuba"); $oldCollection = $oldDb->selectCollection('infosms_past_infos'); $newCollection = $newDb->selectCollection('mc_info_sms_infos'); $oldItems = $oldCollection->find(); foreach ($oldItems as $oldItem) { // Ignore duplicated if (in_array($oldItem['_id'], ['5560cfd83a264', '5559ee4fbcaf3'])) { continue; } // Ignore topic "Resultados" if (in_array('55573f7ad089b', $oldItem['topics'])) { continue; } // Ignore topic "Liga francia" if (in_array($oldItem['_id'], ['556c5de0adfdd', '5559f282f16dc'])) { continue; } // Ignore topic "Champions" if (in_array($oldItem['_id'], ['55704dbff31dc'])) { continue; } $topics = []; // "Pelota" if (in_array('55704c96e0835', $oldItem['topics'])) { $topics = ['55704c96e0835']; } // "Liga Española" if (in_array('55573fae42e4d', $oldItem['topics'])) { $topics = ['55573fae42e4d']; } // "Liga Alemana" if (in_array($oldItem['_id'], ['556c5c08c7e26', '5560ccc7e787b', '5559f236c6c13'])) { $topics[] = '55573fc0e4b4b'; } // "Liga Italiana" if (in_array($oldItem['_id'], ['556c954c65057', '55676cad50d25', '5560cdb6d08a1', '555cfb26917c6', '5559f09c70e23', '5557552d8589a', '55574326465c0', '556f181c80784'])) { $topics[] = '55573fc0f5a5c'; } // "Liga Inglesa" if (in_array($oldItem['_id'], ['556c5e09b8baf', '556c5df285087', '55636d1e17c77', '555ce26d61c7f', '5559f1fb5e58d', '5557422b694b8', '55574326465c0', '557c34084bfde', '55817e04e863f', '5585724cb32b6', '558ab96b1b202'])) { $topics[] = '55573fc0e4c3a'; } // "Selecciones nacionales" if (in_array('5557400e229c5', $oldItem['topics'])) { $topics[] = '5557400e229c5'; } if (!$topics) { var_dump($oldItem['_id']); die; } $newCollection->insert(['id' => $oldItem['_id'], 'body' => $oldItem['body'], 'topics' => $topics, 'created' => $oldItem['created']]); } }
/** * @return void */ public function __construct($options) { if (!extension_loaded('mongo')) { \Zend_Cache::throwException('The MongoDB extension must be loaded for using this backend !'); } parent::__construct($options); // Merge the options passed in; overridding any default options $this->_options = array_merge($this->_options, $options); $this->_conn = new \MongoClient($this->getServerConnectionUrl()); $this->_db = $this->_conn->selectDB($this->_options['dbname']); $this->_collection = $this->_db->selectCollection($this->_options['collection']); $this->_collection->ensureIndex(array('t' => 1), array('background' => true)); $this->_collection->ensureIndex(array('expires_at' => 1), array('background' => true)); }
/** * Implement configurations for MongoDB connection * * @param \Phalcon\Config $config * @throws \MongoConnectionException */ public function __construct(\Phalcon\Config $config) { try { if (!$this->db) { // init client $this->client = new \MongoClient($this->getConnectUri($config)); // select database $this->db = $this->client->selectDB($config['dbname']); } // select collection $this->setCollection(); } catch (\MongoConnectionException $e) { throw new \MongoConnectionException($e->getMessage()); } }
public function testConnections() { $client = new MongoClient(); $db1 = $client->selectDB('activemongo2_tests'); $db2 = $client->selectDB('activemongo2_tests_foobar'); $cols1 = array_map(function ($a) { return (string) $a; }, $db1->listCollections()); $cols2 = array_map(function ($a) { return (string) $a; }, $db2->listCollections()); $this->doTest($cols1, $cols2); $this->doTest($cols2, $cols1); $this->assertTrue(in_array('activemongo2_tests_foobar.zzzz.user', $cols2)); }
/** * @see MongoClient#selectDB */ public function selectDB($name) { if (!empty($name)) { $this->dbname = $name; } return parent::selectDB($this->dbname); }
function setupmongo() { //sets up a mongo connection $mongo = new MongoClient("mongodb://*****:*****@localhost/backendtest"); $collection = $mongo->selectDB('backendtest')->selectCollection('user'); return $collection; }
function setDatabase($di, $host, $db) { $di->set('api_db', function () use($host, $db) { $mongo = new MongoClient($host); return $mongo->selectDB($db); }, true); }
public function register(Application $app, array $config = []) { // apply default options $defaultClientOptions = ['server' => 'mongodb://localhost:27017', 'options' => ['connect' => true], 'driver_options' => []]; if (isset($app['mongodb.mongo_client_options'])) { $app['mongodb.mongo_client_options'] = array_merge($defaultClientOptions, $app['mongodb.mongo_client_options']); } else { $app['mongodb.mongo_client_options'] = $defaultClientOptions; } // apply config parameter if (isset($config['mongodb.mongo_client_options'])) { $app['mongodb.mongo_client_options'] = array_merge($app['mongodb.mongo_client_options'], $config['mongodb.mongo_client_options']); } if (isset($config['mongodb.db'])) { $app['mongodb.db'] = $config['mongodb.db']; } // create service container $app['mongodb.mongo_client'] = $app->share(function () use($app) { $mongoClient = new \MongoClient($app['mongodb.mongo_client_options']['server'], $app['mongodb.mongo_client_options']['options'], $app['mongodb.mongo_client_options']['driver_options']); if (isset($app['mongodb.db'])) { $mongoClient->selectDB($app['mongodb.db']); } return $mongoClient; }); }
function goForIt() { $mongo = new MongoClient(); $emails = $mongo->selectDB('emails_tester')->selectCollection('emails'); $servers = ['tcp://gmail-smtp-in.l.google.com:25', 'tcp://alt1.gmail-smtp-in.l.google.com:25', 'tcp://alt2.gmail-smtp-in.l.google.com:25', 'tcp://alt3.gmail-smtp-in.l.google.com:25', 'tcp://alt4.gmail-smtp-in.l.google.com:25']; /** @var Client[] $clients */ $clients = []; $loop = React\EventLoop\Factory::create(); $logger = new \Zend\Log\Logger(); $writer = new \Zend\Log\Writer\Stream('php://output'); $logger->addWriter($writer); $logger->info('Creating clients.'); $start = microtime(1); $checked = 0; for ($i = 0; $i < 100; $i++) { $client = new Client($loop, function ($record) use(&$checked, $emails, $start, $logger) { $record['state'] = 'valid'; $emails->save($record); $checked++; if ($checked % 1000 == 0) { $logger->info("Checked: {$checked}. Speed: " . $checked / (microtime(1) - $start) . " emails/sec."); } }, function ($record, $reason) use(&$checked, $emails, $start, $logger) { $record['state'] = 'invalid'; $emails->save($record); if ($reason !== false) { $logger->warn("Email <{$record['email']}> failed check: {$reason}"); } $checked++; if ($checked % 1000 == 0) { $logger->info("Checked: {$checked}. Speed: " . $checked / (microtime(1) - $start) . " emails/sec."); } }); $clients[] = $client; } $logger->info('Done.'); $loop->addPeriodicTimer(0.001, function () use($clients, $emails, $servers, $logger) { foreach ($clients as $c) { if ($c->getState() === Client::STATE_DISCONNECTED) { $logger->info(spl_object_hash($c) . ": connecting..."); $c->connect($servers[mt_rand(0, count($servers) - 1)]); return; } if ($c->getState() === Client::STATE_BUSY) { continue; } if ($c->getState() === Client::STATE_IDLE) { $record = $emails->findOne(['state' => ['$exists' => false]]); if (!isset($record['email'])) { continue; } $record['state'] = 'in_progress'; $emails->save($record); $c->checkEmail($record); continue; } } }); $loop->run(); }
/** * $dsn has to contain db_name after the host. E.g. "mongodb://localhost:27017/mongo_test_db" * * @static * * @param $dsn * @param $user * @param $password * * @throws ModuleConfigException * @throws \Exception */ public function __construct($dsn, $user, $password) { /* defining DB name */ $this->dbName = substr($dsn, strrpos($dsn, '/') + 1); if (strlen($this->dbName) == 0) { throw new ModuleConfigException($this, 'Please specify valid $dsn with DB name after the host:port'); } /* defining host */ if (false !== strpos($dsn, 'mongodb://')) { $this->host = str_replace('mongodb://', '', $dsn); } else { $this->host = $dsn; } $this->host = rtrim(str_replace($this->dbName, '', $this->host), '/'); $options = ['connect' => true]; if ($user && $password) { $options += ['username' => $user, 'password' => $password]; } try { $m = new \MongoClient($dsn, $options); $this->dbh = $m->selectDB($this->dbName); } catch (\MongoConnectionException $e) { throw new ModuleException($this, sprintf('Failed to open Mongo connection: %s', $e->getMessage())); } $this->dsn = $dsn; $this->user = $user; $this->password = $password; }
/** * Return a new Database instance. * * If a logger callable was defined, a LoggableDatabase will be returned. * * @see Connection::selectDatabase() * @param string $name * @return Database */ protected function doSelectDatabase($name) { $mongoDB = $this->mongoClient->selectDB($name); $numRetries = $this->config->getRetryQuery(); $loggerCallable = $this->config->getLoggerCallable(); return $loggerCallable !== null ? new LoggableDatabase($this, $mongoDB, $this->eventManager, $numRetries, $loggerCallable) : new Database($this, $mongoDB, $this->eventManager, $numRetries); }
function __construct($databaseName) { $server = "mongodb://localhost:27017/"; $m = new MongoClient($server); $this->db = $m->selectDB($databaseName); $this->postsCollection = $this->db->selectCollection('testposts'); }
public function connect() { // Connect to the database and return the collection $mongo = new MongoClient('mongodb://localhost'); $db = $mongo->selectDB('test'); return $db->selectCollection('locations'); }
function get_connection() { $connecting_string = sprintf('mongodb://%s:%d/%s', HOST, POST, DB); $connection = new MongoClient($connecting_string); $connection->selectDB("test"); return $connection; }
public function execute() { parent::execute(); // Make sure all required parameters are used $required_parameters = array('id'); foreach ($required_parameters as $parameter) { if (!array_key_exists($parameter, $_GET)) { echo json_encode(array('error' => 'Missing parameter: \'' . $parameter . '\'')); exit; } } // Initialize database try { $m = new \MongoClient('mongodb://' . MONGODB_USERNAME . ':' . MONGODB_PASSWORD . '@' . MONGODB_HOST . '/' . MONGODB_DATABASE); $db = $m->selectDB(MONGODB_DATABASE); } catch (MongoConnectionException $e) { echo json_encode(array('error' => 'Database connection failed, please try again later')); exit; } // Query database $result = $db->interactions->findOne(array('_id' => new MongoId($_GET['id']))); // Output JSON data if (is_null($result)) { echo json_encode(array('error' => 'Message doesn\'t exist')); } else { echo json_encode($result); } }
function sendMongo($steamId, $type) { //function mongoConnect($steamId,$type,$collection){ switch ($type) { case 1: //gets the player Summaries $fetch_pInfo = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?\t\tkey=238E8D6B70BF7499EE36312EF39F91AA&steamids={$steamId}"; break; case 2: //gets the players Game Library $fetch_pInfo = "http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=238E8D6B70BF7499EE36312EF39F91AA&steamid={$steamId}&format=json"; break; /* case 3://gets the players achievements //steam api for players achievements. break; case 4://may have to get other stats, //will use this maybe for players over all steam rank. break; */ } //end switch data $jsonO = file_get_contents($fetch_pInfo); var_dump($jsonO); $connection = new MongoClient("mongodb://*****:*****@ds041643.mongolab.com:41643/steamdata"); $mongodb = $connection->selectDB('steamdata'); $collection = new MongoCollection($mongodb, 'gameLibrary'); //var_dump($connection); //var_dump($collection); $send = array(); $send["_id"] = $steamId; $send["info"] = $jsonO; $collection->insert($send); }
function getCollection() { global $_server_name2, $_server_port2; $m = new MongoClient("{$_server_name2}:{$_server_port2}"); $db = $m->selectDB("mysqlTableComment"); return $db->fieldComment; }
public function __construct() { parent::__construct(); $mg_instance = new MongoClient(Kohana::config('uap.mongodb')); $mongo = $mg_instance->selectDB(MONGO_DB_FEED); $this->mongo_deal = $mongo->selectCollection('deals'); }
public static function MDB() { // C('Mongo')['username']; // C('Mongo')['password']; $connection = new MongoClient(C('Mongo')['host']); return $connection->selectDB(C('Mongo')['database_name']); }
public static function factory($cfg) { if ($cfg instanceof Traversable) { $cfg = ArrayUtils::iteratorToArray($cfg); } if (!is_array($cfg)) { throw new \Exception('配置信息未设定'); } if (!isset($cfg['cluster']) || empty($cfg['cluster'])) { throw new \Exception('配置信息中缺少cluster参数'); } $options = array(); //$options['connectTimeoutMS'] = 60000; //$options['socketTimeoutMS'] = 60000; //$options['w'] = 1; // $options['w'] = 3; //$options['wTimeout'] = 60000; if (isset($cfg['options']) && !empty($cfg['options'])) { $options = array_merge($options, $cfg['options']); } if (!isset($cfg['cluster']['default']) || empty($cfg['cluster']['default'])) { throw new \Exception('配置信息中缺少cluster.default参数'); } $cluster = array(); foreach ($cfg['cluster'] as $clusterName => $clusterInfo) { try { shuffle($clusterInfo['servers']); $dnsString = 'mongodb://' . join(',', $clusterInfo['servers']); if (class_exists('\\MongoClient')) { $connect = new \MongoClient($dnsString, $options); $connect->setReadPreference(\MongoClient::RP_PRIMARY_PREFERRED); // 读取数据主优先 // $connect->setReadPreference(\MongoClient::RP_SECONDARY_PREFERRED);//读取数据从优先 $cluster[$clusterName]['connect'] = $connect; } else { throw new \Exception('请安装PHP的Mongo1.4+版本的扩展'); } } catch (\Exception $e) { if ($clusterName == 'default') { throw new \Exception('无法与Mongodb建立连接' . $e->getMessage()); } else { break; } } try { if (is_array($clusterInfo['dbs']) && !empty($clusterInfo['dbs']) && $connect instanceof \MongoClient) { foreach ($clusterInfo['dbs'] as $db) { $cluster[$clusterName]['dbs'][$db] = $connect->selectDB($db); } } else { throw new \Exception('请设定cluster.name.dbs'); } } catch (\Exception $e) { throw new \Exception('已经建立连接,但是无法访问指定的数据库'); } unset($connect); } return new Config($cluster); }
function dataBaseCall($collectionName) { $m = new MongoClient(); $db = $m->selectDB('SocialMedia'); $collection = new MongoCollection($db, $collectionName); $cursor = $collection->find(); return $cursor; }
function getConnection() { $uri = "mongodb://*****:*****@xxxxxx.mongolab.com:31988/books"; $options = array("connectTimeoutMS" => 30000); $client = new MongoClient($uri, $options); $db = $client->selectDB("books"); return $db; }