I've installed MongoDB on a server. What now? - mongodb

I'm interesting in playing around with NoSQL and particularly MongoDB. To this end, I've installed MongoDB on an external Linux box by SSHing into the server and running the following command:
sudo pecl install mongo
Mongo seems to have installed correctly and there's now a 'Mongo' section if I run phpinfo().
But what now? I seem to be having trouble going from here to using it in production. The problem being, I don't think the MongoDB service is running, and I haven't configured any MongoDB users because I'm not sure how to. As a result, the following test script fails:
<?php
// connect
$m = new Mongo();
// select a database
$db = $m->comedy;
// select a collection (analogous to a relational database's table)
$collection = $db->cartoons;
// add a record
$obj = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );
$collection->insert($obj);
// add another record, with a different "shape"
$obj = array( "title" => "XKCD", "online" => true );
$collection->insert($obj);
// find everything in the collection
$cursor = $collection->find();
// iterate through the results
foreach ($cursor as $obj) {
echo $obj["title"] . "\n";
}
?>
As I get the following error message:
Fatal error: Uncaught exception 'MongoConnectionException' with message 'connecting to failed: Transport endpoint is not connected' in /home/[username]/public_html/mongodbtest/index.php:4 Stack trace: #0 /home/[username]/public_html/mongodbtest/index.php(4): Mongo->__construct() #1 {main} thrown in /home/woohoobi/public_html/mongodbtest/index.php on line 4
How can I get from here to using MongoDB?

You never actually installed MongoDB, but rather the PHP extension that lets you connect to a MongoDB instance. Install MongoDB by downloading it and installing it on your server, and then connect to it from your PHP script.

Related

Using Jenssegers MongoDB with Slim and Capsule

I am using the Slim 4 framework along with Jenssegers MongoDB library and Capsule (Illuminate\Database from Laravel). I have got the MongoDB extension installed on my Linux server and everything seems ok connection wise, but I cannot seem to insert data into the database or get anything from it. I have tried with the query builder and Eloquent. My code with query builder example is below.
use Illuminate\Database\Capsule\Manager as Capsule;
$capsule = new Capsule;
$capsule->getDatabaseManager()->extend('mongodb', function($config, $name) {
$config['name'] = $name;
return new \Jenssegers\Mongodb\Connection($config);
});
$capsule->addConnection([
'host' => '127.0.0.1',
'port' => 27017,
'database' => 'testing',
'username' => '',
'password' => '',
], 'mongodb');
// Set the event dispatcher used by Eloquent models... (optional)
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;
$capsule->setEventDispatcher(new Dispatcher(new Container));
// Make this Capsule instance available globally via static methods... (optional)
$capsule->setAsGlobal();
// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
$capsule->bootEloquent();
$capsule->connection('mongodb')->collection('testing')->insert([
'test1'=>'hello',
'test2'=>'world',
]);
The database and collection exist as I can see them in Compass. Can anyone see where I'm going wrong with the code or is it a configuration issue?
There were two problems, one was the driver missing as you point out, but the other was the fact my PHP is running in Linux using Vagrant and it was pointing to localhost, but the MongoDB server is running on the Windows machine and not Linux. Thanks.

Meteor MongoDB database localhost vs server

I made a site with Meteor and it works perfectly on localhost, but not on the server. I have a collection in my mongoDB that I fill using a python-script, this script filled both my local as server mongoDB. I can see that it is filled using a database manager. However the call in my localhost prints an array with the documents, the same code/action on the website on the server returns an empty array.
I really have no clue what the problem could be, somebody that can help me figure this out?
python-script, same for local as on server!
def write_data(documents, collection_name):
# when running locally
#client = pymongo.MongoClient("localhost", 3001)
#db = client.meteor
# on the server
client = MongoClient(mongoURL, username=****,
password=****)
db = client.mercurius
if collection_name in db.collection_names():
collection = db[collection_name]
collection.drop()
new_collection = db[collection_name]
new_collection.insert_many(documents)
cursor = new_collection.find({})
for document in cursor:
print(document)
I use mup to setup the containers, it works for the other things, my code. mongoURL in mup is same as in this script above.
Meteor.call( 'getDBinfo', function(err, response){
console.log(response);
console.log(err);
});
The above call in meteor returns a full array(53 documents) on localhost, empty on server. Both have an undefined err.

Eloquent innodb - SQLSTATE[42S02]: Base table or view not found Table doesn't exist

I have this weird crash and trying for few hours to solve with no success, check everywhere on the internet and didn't find a solution.
I am running Eloquent (without laravel). I have two servers (frontend and backend). The DB is in the backend server.
I am running the exact same code to connect to the database using laravel from both servers. From the backend server everything works. In the frontend server, I get mixed result. Out of 9 tables:
three works, and I am able to retrieve the data.
three return [items:protected] => Array (), while table has data to return.
three cause fatal error SQLSTATE[42S02]: Base table or view not found Table doesn't exist
from #1 I understand that this is not related to issue with database user/password.
for #2, I checked the queries using getQueryLog(), and I run the queries in phpmyadmin, and they work.
from what I observed so far, all the tables that cause #3 are all InnoDB. Why my other tables are MyIsam I don't know.
And the exact same code works in the backend server, so it is not an issue with tables names are in singular or some other code related issue.
backend server is php 5.5.9, eloquent 5.4.45
frontend server is php 5.6.32, eloquent 5.4.36
Any idea what to do about #2 (return data empty) and #3 (php fatal error)?
Ok, found this crazy bug(s).
First, I found out that we had an old version of the database on the frontend server. It was not supposed to be there, so I didn't even think about it as a possibility.
In addition, there was a problem in the code:
$dbhost = __MYSQLDB_HOST__;
$dbuser = 'xxxxx';
$dbpass = 'xxxxx';
$dbname = 'xxxxx';
$capsule = new Capsule;
$capsule->addConnection(array(
'driver' => 'mysql',
'host' => 'localhost', // <= this is the problem!!!
'database' => $dbname,
'username' => $dbuser,
'password' => $dbpass,
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => ''
));
As you can see, when connecting to the database it used localhost instead of the $dbhost variable which contained the remote database host on the backend server.

Uncaught exception 'MongoConnectionException'

Fatal error: Uncaught exception 'MongoConnectionException' with message
'Failed to connect to: localhost:27017: Permission denied' in
/var/www/html/test.php:8 Stack trace: #0 /var/www/html/test.php(8):
MongoClient->__construct() #1 {main} thrown in /var/www/html/test.php
on line 8
Hi Mongo experts...
I am a developer wanting to try out MongoDB. So installed centoOS 6.5 64bit in a test machine (Dell E520 Intel Dual Core 4GB Ram), installed PHP (Apache was already present).
Then installed MongoDB (yum install mongo-10gen mongo-10gen-server), then installed "pecl install mongo" (install ok: channel://pecl.php.net/mongo-1.4.5), added extension=mongo.so to php.ini.
To install pecl, I installed few other things like C++ compiler & php-pear. php5-dev & php5-cli was not available in yum so installed php-devel & php-cli (installed versions are php-devel-5.3.3-27.el6_5.x86_64 & php-cli-5.3.3-27.el6_5.x86_64
I turned off iptables firewall. Ran mongo --host localhost:27017 from shell & connected without problems
[root#localhost ~]# mongo --host localhost:27017
MongoDB shell version: 2.4.8
connecting to: localhost:27017/test
>
These are the contents of test.php
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
// connect
$m = new MongoClient();
//$m = new MongoClient("mongodb://localhost:27017");
// select a database
$db = $m->comedy;
// select a collection (analogous to a relational database's table)
$collection = $db->cartoons;
// add a record
$document = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );
$collection->insert($document);
// add another record, with a different "shape"
$document = array( "title" => "XKCD", "online" => true );
$collection->insert($document);
// find everything in the collection
$cursor = $collection->find();
// iterate through the results
foreach ($cursor as $document) {
echo $document["title"] . "\n";
}
?>
As you can see I have tried both
$m = new MongoClient(); & $m = new MongoClient("mongodb://localhost:27017");
But I am getting the same error. Where am I going wrong?
This problem is documented at http://ca3.php.net/manual/en/mongo.installation.php#mongo.installation.fedora
Red Hat,Fedora and CentOS:
The default Apache settings on these systems do not let requests make network connections, meaning that the driver will get "Permission denied" errors when it tries to connect to the database. If you run into this, try running:
$ /usr/sbin/setsebool -P httpd_can_network_connect 1
Then restart Apache. (This issue has also occurred with SELinux.)
Thanks for all your support!
Hope this thread helps someone from going in circles!

problems using Zend_Db when running php as cli script

I am trying to add some administration scripts to a Zend Framework project, that will end up being run nightly via cron.
However I've hit my first problem with the script when trying to use Zend_Db. I am currently doing a very simple SQL call to get some results and just display them using var_dump() however I get the following error message:
SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
The script so far looks like this:
<?php
chdir(dirname(__FILE__));
error_reporting(E_ALL|E_STRICT);
ini_set('display_errors', 1);
date_default_timezone_set('Europe/London');
//directory setup and class loading
set_include_path('.' . PATH_SEPARATOR . '../library/' . PATH_SEPARATOR . '../application/models/'
. PATH_SEPARATOR . '../library/MyApp/'
. PATH_SEPARATOR . get_include_path());
include "Zend/Loader/Autoloader.php";
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->setFallbackAutoloader(true);
//start sessions
Zend_Session::start();
//read configuration data
$config = new Zend_Config_Xml('../application/config/config.xml', 'app');
//we create an ability to capture errors and write them to an error log if there are problems.
$log = new Zend_Log();
$writer = new Zend_Log_Writer_Stream($config->log->logfile);
$log->addWriter($writer);
$filter = new Zend_Log_Filter_Priority((int)$config->log->level);
$log->addFilter($filter);
//we now need to get the list of graduates that need to have their CV's removed from the search engine
$date = new Zend_Date();
$date->sub(3, Zend_Date::MONTH);
echo $date->get(Zend_Date::ISO_8601);
$sql = "SELECT userid, guid FROM users WHERE lastlogin = ? AND active = 1";
$db = Zend_Db::factory($config->database);
try{
$results = $db->fetchAll($sql, $date->get(Zend_Date::ISO_8601));
var_dump($results);
}catch(Zend_Db_Exception $dbe){
$log->debug($dbe->getMessage()."\n".$dbe->getTraceAsString());
}
//close database.
if($db->isConnected()){
$db->closeConnection();
}
What am I missing? I know that the database connection settings in the Zend_Config object works and the web application is running fine with no issues.
I am running this using Zend Framework v1.7.6 at present.
Also are there any generic tips for using the Zend Framework in a cli script?
Many thanks.
PHP will try to connect to mysql via tcp/ip, unless the mysql server is on the same machine as the script and "localhost" is used as the db host. Then it will use a filesystem socket.
It could be that mysql cannot create /tmp/mysql.sock due to permissions, or that it's not configured to do so. The Mysql manual should have more on that.
A quick way to get around this for now should be to change the db host in your Zend_Db settings to an actual ip mysql listens on, not "localhost" or "127.0.0.1".
also check your php.ini and look for the mysql_sock
this is often a trap for Mac users with Mamp installed: Snow Leopard comes with a php configured which is separate to the ph included with Mamp