RDlab@lsi.upc.edu
February 2014
Welcome to LSI.
This document will cover how to establish connection with the MongoDB server. It will show how to access in text mode through the command line and connection examples for PHP and JAVA.
Server name: mongodb-rdlab.lsi.upc.edu
Puerto: 27017
You can get a username and password by mail at rdlab@lsi.upc.edu or by web at http://rdlab.lsi.upc.edu/index.php/en/services/resources-request.html
NOTE: Database name will be the same as your username.
In order to connect in textual mode (terminal or Command Line Interface) we can type this command while in a Unix system:
mongo mongodb-rdlab.lsi.upc.edu
This way a connection with the server will be established, but it is still necessary to authenticate against the database:
use <database>
db.auth(“<username>”,”<password>”)
With “show collections;” we can check if we can list the contents of our database:
show collections
Prior to establishing the connection , it is necessary to prepare the system and install the MongoDB PHP library
sudo apt-get install php-pear php5-dev libpcre3-dev
sudo pecl install mongodb
You should add "extension=mongodb.so" to php.ini
/etc/php5/apache2/php.ini
/etc/php5/cli/php.ini
If we want to establish connection from a PHP environment, we can do it by using the next code snippet:
$host = "mongodb-rdlab.lsi.upc.edu";
$username = "<username>";
$password = "<password>";
$database = "<database>";
$manager = new MongoDB\Driver\Manager("mongodb://$username:$password@$host:27017/$database");
$query = new MongoDB\Driver\Query(array(), array());
$rows = $manager->executeQuery("$database.system.users", $query);
foreach($rows as $r){
print_r($r);
}
If it works, running the script will produce the following output:
stdClass Object
(
[_id] => MongoDB\BSON\ObjectID Object
(
[oid] => orh9qufhsdkfakfiasfhkjff
)
[user] => <username>
[readOnly] =>
[pwd] => 9847ifhif9238rf923ry9fisdhf938yr
)
To establish connection from a java project, it is necessary to download the driver mongo-java-driver-2.10.1.jar, add it to the CLASSPATH and import it with the commands:
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
Then, execute this snipped to connect:
String server = "mongodb-rdlab.lsi.upc.edu";
String username = "<username>";
String password = "<password>";
String database = "<database>";
MongoClient mongoClient = new MongoClient(server);
DB db = mongoClient.getDB(database);
boolean auth = db.authenticate(username,password.toCharArray());
In order to know if it has worked correctly, we can try to list our collections:
Set<String> colls = db.getCollectionNames();
for (String s : colls) {
System.out.println(s);
}