How to Connect to a Mongo Replica Set Using Python?

Estimated read time 2 min read

To connect to a MongoDB replica set using Python, you can use the pymongo library, which is the official MongoDB driver for Python. Here’s an example of how to establish a connection to a MongoDB replica set:

from pymongo import MongoClient

# Specify the connection details
replica_set_name = 'my_replica_set'
mongodb_host = 'mongodb://host1:port1,host2:port2,host3:port3/?replicaSet=' + replica_set_name

# Connect to the replica set
client = MongoClient(mongodb_host)

# Access a specific database
db = client['my_database']

# Access a collection within the database
collection = db['my_collection']

# Perform operations on the collection
# For example, insert a document
document = {'name': 'John Doe', 'age': 30}

# Close the connection when done

In the code snippet above, you need to provide the following information:

  • replica_set_name: The name of your MongoDB replica set.
  • mongodb_host: The connection string that specifies the hosts and ports of the replica set members, separated by commas. Make sure to include the replicaSet parameter followed by the replica set name.

Once you establish the connection, you can interact with the replica set using the client object. In the example above, a specific database (my_database) and collection (my_collection) are accessed. You can perform various operations like inserting, querying, updating, or deleting documents within the collection.

Remember to close the connection using client.close() when you’re finished with the replica set to free up resources.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply