Connecting to a Database
As useful as Simon is, it's of no use without a database connection. Connecting to a database can be as simple as specifying its name.
from simon.connection import connect connect(name='simon')
This will connect to the
mongod instance running on
and use the database named
Of course the :meth:`~simon.connection.connect` method can do more than just connect to a database. For starters, it can connect to another database.
This will use the same
mongod instance as before, this time using
the database named
When connecting to a database, each is given an alias. By default, Simon tries to use the name of the database as its alias. If all of your databases are part of the same MongoDB server, this won't be an issue. There may be times, however, when your databases are located in multiple locations. If two databases have the same name, the default alias behavior won't be sufficient. Fortunately you can assign any alias you want.
connect('localhost', name='simon') connect('legacy-server', name='simon', alias='legacy-simon')
This will connect to
localhost and use the
database with the alias
simon. It will also connect to
legacy-server and use the
simon database with the alias
Before moving on to more advanced concepts, there's one more thing to
point out. The first call to :meth:`~simon.connection.connect` will have
two aliases, the name of the database and
default. By default, all
of your Simon models will use this connection.
As a matter of best practice, it's a good idea to use authentication
with your database. The :meth:`~simon.connection.connect` method accepts
connect(name='simon', username='theuser', password='thepassword')
This will fail to connect to the database if the authentication fails.
Another good idea when working with MongoDB is to use replica sets.
:meth:`~simon.connection.connect` accepts a parameter named
replica_set with the name of the replica set to use.
URI Connection String
The :meth:`~simon.connection.connect` method supports connecting to a database using a URI.
Full details are available in the MongoDB Docs.