Connecting to MongoDB Database



As mentioned earlier, you should first start MongoDB server using mongod command.

MongoEngine provides connect() function to connect to a running instance of mongodb server.

from mongoengine import connect
connect(‘mydata.db’)

By default, MongoDB server is running on localhost and on port 27017. To customize, you should provide the host and port arguments to connect() −

connect('mydata.db', host='192.168.1.1', port=12345)

In case the database requires authentication, its credentials such as username, password and authentication_source arguments should be provided.

connect('mydata.db', username='user1', password='***', authentication_source='admin')

MongoEngine also supports URI style connections instead of IP address.

connect('mydata.db', host='mongodb://localhost/database_name')

The connect() function has another optional parameter called replicaset. MongoDB is a distributed database. Data stored in one server is usually replicated in many server instances in order to ensure high availability. A replica set in MongoDB is a group of mongod processes on which the same data set is maintained. Replica sets are the basis for all production deployments.

connect(host='mongodb://localhost/dbname?replicaSet=rs-name')

Following replica set methods are defined as follows:

rs.add() Adds a member to a replica set.
rs.conf() Returns the replica set configuration document.
rs.freeze() Prevents the current member from seeking election as primary for a period of time.
rs.initiate() Initializes a new replica set.
rs.reconfig() Re-configures a replica set by applying a new replica set configuration object.
rs.remove() Removes a member from a replica set.

MongoEngine also allows connection with multiple databases. You need to provide unique alias name for each database. For example, following code connects Python script to two MongoDB databases.

connect(alias='db1', db='db1.db')
connect(alias='db2', db='db2.db')
Advertisements