Mongoengine 简明教程

Connecting to MongoDB Database

如前所述,你应当首先使用 mongod 命令启动 MongoDB 服务器。

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

MongoEngine 提供 connect() 函数以连接到 mongodb 服务器的正在运行的实例。

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

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

默认情况下,MongoDB 服务器在 localhost 上和 27017 端口上运行。若要自定义,你应当向 connect() 提供 host 和 port 参数 −

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)

如果数据库需要身份验证,则应当提供其凭据,例如 username、password 和 authentication_source 参数。

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 还支持 URI 样式的连接,而不是 IP 地址。

MongoEngine also supports URI style connections instead of IP address.

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

connect() 函数有另一个可选的参数,称为 replicaset。MongoDB 是分布式数据库。存储在某一台服务器中的数据通常在许多服务器实例中复制,以确保高可用性。MongoDB 中的 replica set(副本集)是在其上维护相同数据集的 mongod 进程组。Replica set 是所有生产部署的基础。

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 还允许连接多个数据库。你需为每个数据库提供唯一的别名。例如,以下代码将 Python 脚本连接到两个 MongoDB 数据库。

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')