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 localhost and use the database named simon.
Of course the 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 metrics.
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 mongod on localhost and use the simon database with the alias simon. It will also connect to mongod on legacy-server and use the simon database with the alias legacy-simon.
Before moving on to more advanced concepts, there’s one more thing to point out. The first call to 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 connect() method accepts username and password parameters.
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. connect() accepts a parameter named replica_set with the name of the replica set to use.