mongodb - 如何使用replicaset url连接mongodb?

标签 mongodb azure azure-virtual-machine bitnami azure-virtual-network

我在 Azure 上使用带有复制功能的 MongoDB (bitnami)。
我创建了三个 mongodb 节点(1 个主节点、1 个辅助节点和 1 个仲裁节点)。 当我尝试连接 MongoDB 连接 URI (mongodb://username:password@ip01:27017,ip02:27017,ip03:27017/?readPreference=primary&replicaSet=replicaset) 时,它给我错误,如 pymongo.errors.ServerSelectionTimeoutError:10.0.0.5:27017:超时,10.0.0.6:27017:[Errno 113]没有到主机的路由,10.0.0.4:27017:超时,10.0.0.7:27017:超时
我更喜欢这个Official Documentation (Bitnami)连接网址。

connectionString = "mongodb://root:Root123@*.*.*.*:27017,*.*.*.*:27017,*.*.*.*:27017/?replicaSet=replicaset"
client= MongoClient(connectionString)
db = client['mongo_collection']
data = db.xyz.find({"x": 10})
for d in data:
    print d

最佳答案

根据official document您提供的。

Ensure that the application is able to connect to each cluster node using its public or private IP address. To ensure connectivity, you have two options:

Host the application in the same network as the MongoDB cluster so that it can address each node using its private IP address. This is the recommended configuration for production environments. Host the application in a different network and assign public IP addresses, with appropriate firewall rules, to the cluster nodes (if not already assigned by default) so that the application can address each node using its public IP address. This configuration is not recommended for production environments.

因此,如果您在同一个 Azure 虚拟网络中进行测试,则可以使用私有(private) IP(例如 10.0.0.6)。我在我的实验室进行测试,我使用 python example .

import pymongo
client = pymongo.MongoClient("mongodb://root:<passsword>@10.0.0.6:27017,10.0.0.4:27017,10.0.0.5:27017/?replicaSet=replicaset")

db = client.test
>>> db.name
u'test'
>>> db.my_collection
Collection(Database(MongoClient(host=['10.0.0.5:27017', '10.0.0.6:27017', '10.0.0.4:27017'], document_class=dict, tz_aware=False, connect=True, replicaset='replicaset'), u'test'), u'my_collection')
>>> db.my_collection.insert_one({"x": 10}).inserted_id
ObjectId('5987cc0b9e90d52dd1860ac3')

更新:

如果你想连接 mongodb 节点,你应该需要 ping 私有(private) IP。这是一种设计行为。

如果您想从应用程序或本地使用 mongodb,则需要创建站点到站点 VPN 连接或点到站点 VPN 连接。

关于mongodb - 如何使用replicaset url连接mongodb?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45519064/

相关文章:

azure - 访问被拒绝 - 将网络驱动器映射到 azure 文件共享

java - 缺少订阅注册 : The subscription is not registered to use namespace 'Microsoft.Storage'

mongodb - bson 方案的 Virtuals 属性

node.js - 根据条件从 Mongo 中过期/删除文档

c# - 如何使用 Linq 查询 Azure 存储表?

azure - 无法从 ARM 模板检索逻辑应用程序(标准)工作流程 URL

azure - Azure Cosmos DB Gremlin 是否支持存储过程或自定义函数

azure - Azure 上的 Windows Server 2016 恢复出厂设置

javascript - Meteor js - 无法通过控制台在Mongo上插入数据

mongodb - MongoDB 中 $project、$filter 和 $match 之间的区别