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 like($user, $id, $channel) { try { $conn = new MongoClient(); $db = $conn->site; $collection = $db->users; $testquery = array('user_name' => $user); $cursor = $collection->find($testquery); if ($cursor->count() == 0) { $info = array('user_name' => $user, '_id' => $id, 'likes' => 1); $collection->insert($info); $collection->update(array('user_name' => $user), array('$addToSet' => array('liked_channels' => $channel))); echo "liked"; } else { $collection->update(array('user_name' => $user), array('$inc' => array('likes' => 1))); $collection->update(array('user_name' => $user), array('$addToSet' => array('liked_channels' => $channel))); //$collection->update(array('user_name' => $user), array('$addToSet' => array('liked_channels' => $channel), '$setOnInsert' => array('$inc' => array('likes' => 1))), array('upsert' => true)); echo "liked"; } $conn->close(); } catch (MongoConnectionException $e) { echo 'Error connecting to MongoDB server'; } catch (MongoException $e) { echo 'Error somewhere else with mongo'; } //die('Error: ' . $e->getMessage()); } exit; }
protected function getCollection() { if (!$this->coll) { $this->coll = $this->mongoClient->selectCollection($this->dbName, $this->collName); } return $this->coll; }
/** * 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 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 __construct($databaseName) { $server = "mongodb://localhost:27017/"; $m = new MongoClient($server); $this->db = $m->selectDB($databaseName); $this->postsCollection = $this->db->selectCollection('testposts'); }
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); }
/** * 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; }
/** * Retrieves a collection object by name. * * @param string $name * @return \MongoCollection */ public function collection($name) { if (empty($this->collections[$name])) { $this->collections[$name] = new \MongoCollection($this->connection->selectDb($this->dbName), $name); } return $this->collections[$name]; }
/** * {@inheritdoc} * @see http://docs.phalconphp.com/pl/latest/reference/odm.html */ public function register(DiInterface $di) { $di->set(self::SERVICE_NAME, function () use($di) { $mongoConfig = $di->get('config')->mongo->toArray(); if (isset($mongoConfig['dsn'])) { $hostname = $mongoConfig['dsn']; unset($mongoConfig['dsn']); } else { //obtains hostname if (isset($mongoConfig['host'])) { $hostname = 'mongodb://' . $mongoConfig['host']; } else { $hostname = 'mongodb://localhost'; } if (isset($mongoConfig['port'])) { $hostname .= ':' . $mongoConfig['port']; } //removes options that are not allowed in MongoClient constructor unset($mongoConfig['host']); unset($mongoConfig['port']); } $dbName = $mongoConfig['dbname']; unset($mongoConfig['dbname']); $mongo = new \MongoClient($hostname, $mongoConfig); return $mongo->selectDb($dbName); }, true); }
/** * $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; }
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; }); }
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; }
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; }
public function connect($servers, $options = null) { if (empty($servers)) { $this->error('not enough information to connect to mongodb.'); } if (empty($options)) { $options = array('connect' => true); } // checking dependency if (!class_exists('MongoClient')) { $this->error('no mongo client class. remember to sudo pecl install mongo.'); } try { $connection = new MongoClient($servers, $options); $ok = $connection->connect(); if (!$ok) { $this->error('could not connect to mongo.'); } self::$___connection = $connection; } catch (Exception $e) { $this->error('couldn\'t connect to the mongo:' . $e->getMessage()); } $this->log('connected to ' . $servers . '.'); return self::$___connection; }
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(); }
function getCollection() { global $_server_name2, $_server_port2; $m = new MongoClient("{$_server_name2}:{$_server_port2}"); $db = $m->selectDB("mysqlTableComment"); return $db->fieldComment; }
/** * {@inheritdoc} */ public function register(DiInterface $di) { $di->set(self::SERVICE_NAME, function () use($di) { $mongo = new \MongoClient(); return $mongo->selectDb($di->get('config')->mongo->db); }, true); }
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 __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 function disconnect() { if ($this->_connection) { $this->_connection->close(); } $this->_db = $this->_connection = NULL; }
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); }
public function __construct() { parent::__construct(); $mg_instance = new MongoClient(Kohana::config('uap.mongodb')); $this->m = $mg_instance->selectDB(MONGO_DB_FEED); $this->comment = $this->m->selectCollection('comment_new'); $this->comment_new = $this->m->selectCollection('comment_new'); }
function dataBaseCall($collectionName) { $m = new MongoClient(); $db = $m->selectDB('SocialMedia'); $collection = new MongoCollection($db, $collectionName); $cursor = $collection->find(); return $cursor; }
/** * Creates a new collection * * @param MongoDB $db - Parent database. * @param string $name - * * @return - Returns a new collection object. */ public function __construct(MongoDB $db, $name) { $this->db = $db; $this->name = $name; $this->fqn = $db->_getFullCollectionName($name); $this->client = $db->_getClient(); $this->protocol = $this->client->_getProtocol(); }
function getConnection() { $uri = "mongodb://*****:*****@xxxxxx.mongolab.com:31988/books"; $options = array("connectTimeoutMS" => 30000); $client = new MongoClient($uri, $options); $db = $client->selectDB("books"); return $db; }
/** * Return the mongo collection with given name * * @param $name * @return \MongoCollection */ protected function getCollection($name) { if (!$this->db) { global $config; $this->setDb(MongoProvider::getClient($config['db']['host'], array())); } return $this->db->selectCollection('shortener', 'links'); }