- MongoEngine - Discussion
- MongoEngine - Useful Resources
- MongoEngine - Quick Guide
- MongoEngine - Extensions
- MongoEngine - Text Search
- MongoEngine - Signals
- MongoEngine - GridFS
- MongoEngine - Javascript
- MongoEngine - Atomic Updates
- MongoEngine - Document Inheritance
- MongoEngine - Advanced Queries
- MongoEngine - Aggregation
- MongoEngine - Indexes
- MongoEngine - Custom Query Sets
- MongoEngine - Sorting
- MongoEngine - QuerySet Methods
- MongoEngine - Query Operators
- MongoEngine - Filters
- MongoEngine - Querying Database
- MongoEngine - Add/Delete Document
- MongoEngine - Fields
- MongoEngine - Dynamic Schema
- MongoEngine - Document Class
- MongoEngine - Connecting to MongoDB Database
- MongoEngine - Installation
- MongoEngine - Object Document Mapper
- MongoEngine - MongoDB Compass
- MongoEngine - MongoDB
- MongoEngine - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Connecting to MongoDB Database
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