Connecting to MongoDB Database

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
# Simple connect just connect as defualt to own mongo host on local machine
connect(db='project1')

By default, MongoDB server is running on localhost and on port 27017.

connect(db='project1', host='127.0.0.1', port=27017)

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

from mongoengine import connect
connect(
db='project1',
host='127.0.0.1',
port=27017,
username='mongoadmin',
password='secret',
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.
```python
from mongoengine import connect
connect(
db='project1',
host='127.0.0.1',
port=27017,
username='mongoadmin',
password='secret',
authentication_source='admin',
alias='project1'
)
connect(
db='project2',
host='127.0.0.1',
port=27017,
username='mongoadmin',
password='secret',
authentication_source='admin',
alias='project2'
)
```

MongoEngine – Installation (Prev Lesson)
(Next Lesson) MongoEngine – Document Class
', { 'anonymize_ip': true });