Working with ObjectRocket database - adasilva/waterYourWallet Wiki

Working with the ObjectRocket database

See ObjectRocket documentation for mongodb

Connecting to your own ObjectRocket database

Each ObjectRocket instance comes with a connect string which identifies the instance. Each instance can contain multiple databases. For example in my instance, there is one database called waterwallet, which contains one collection, plants.

To connect to your object rocket database, first identify the connect string. This is posted in the database details, and looks something like w-mongos0.objectrocket.com See docs. Next, use the ObjectRocket interface to set up a username and password for yourself. The connection URI will be:

db_uri = 'mongodb://username:[email protected]_string/dbname'

where username and password are the username and password, connect_string is the connect string, and dbname is the name of the database. Remember, if you type your username and password into any file, do not upload it to github.

You can connect to the database with read-only access using,

from pymongo.read_preferences import ReadPreference
conn = pymongo.MongoClient(db_uri,port=37013,read_preference=ReadPreference.SECONDARY_PREFERRED))

(You may need to change the port argument.) ObjectRocket instance is actually a collection of "replicas." This set of replicas includes one primary, one or more secondaries, and one arbiter (which helps choose a primary in case there isn't one.) (I'm not sure if the next sentence is entirely correct) In the connection to the client above, we are only connecting to the set of secondaries, so we have to set the read preference to allow us to read from a secondary replica. There are other available read preferences, for example PRIMARY_PREFERRED and NEAREST. By default, the client will not read from a secondary replica, and if we try to look for entries, we'll get an error.

Now we can try out some queries. For example,

db = conn.waterwallet
plants = db.plants
plants.find_one()

When you're done, remember to close the connection,

conn.close()

So far we can only read from the database. To write to the database, we need to connect to the primary replica set. The replica set identification is the long string located near your conenction string. For example, in xxxxxxxxx/dfw-c9-0.objectrocket.com:37013, the connection string is dfw-c9-0.objectrocket.com, the port is 37013, and the primary replica set is identified by the x's (which will be a series of numbers and letters). Connect to the primary by running the following, after replacing rs below with the replica set identification string,

conn = pymongo.MongoClient(db_uri,port=37013,replicaSet=rs)

With this connection we can read and write from the database! Try running the insert operations in local_database_setup.py with the local database connection replaced by your remote connection.