English 中文(简体)
MongoEngine - Connecting to MongoDB Database
  • 时间:2024-11-03

Connecting to MongoDB Database


Previous Page Next Page  

As mentioned earper, 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 reppcaset. MongoDB is a distributed database. Data stored in one server is usually reppcated in many server instances in order to ensure high availabipty. A reppca set in MongoDB is a group of mongod processes on which the same data set is maintained. Reppca sets are the basis for all production deployments.


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

Following reppca set methods are defined as follows:

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

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


connect(apas= db1 , db= db1.db )
connect(apas= db2 , db= db2.db )
Advertisements