I am trying to connect mongodb using pymongo. I see two classes to connect to mongodb.
MongoClient and Connection.
What is the difference of these two classes?
The use of the PyMongo driver with MongoClient class makes it easier to code and connect to MongoDB easily and quickly. MongoClient is a part of the PyMongo library and it can be imported to the Python code using the “ from pymongo import MongoClient “.
class pymongo.mongo_client. MongoClient (host='localhost', port=27017, document_class=dict, tz_aware=False, connect=True, **kwargs) ¶ Client for a MongoDB instance, a replica set, or a set of mongoses. The client object is thread-safe and has connection-pooling built in.
MongoClient (host='localhost', port=27017, document_class=dict, tz_aware=False, connect=True, **kwargs) ¶ Client for a MongoDB instance, a replica set, or a set of mongoses. The client object is thread-safe and has connection-pooling built in.
Similarly, you can also install PyMongo 3.8 using PIP for Python 3 by executing the command in the python3 environment: 1 sudo python3 -m pip install pymongo == 3.8.0 NOTE: As of June 2019, PyMongo version 3.8 is the latest stable release of the Python driver.
MongoClient
is the preferred method of connecting to a mongo instance. The Connection
class is deprecated. But, in terms of use they are very similar.
MongoClient and Connection are similar but MongoClient was introduced (since mongodb 2.2+ onwards) to mainly support WriteConcern
and other features.
Connection
is depreciated, so avoid using it in future.
The first step when working with PyMongo is to create a MongoClient
to the running mongod instance. Doing so is easy:
>>> from pymongo import MongoClient
>>> client = MongoClient()
The above code will connect on the default host and port. We can also specify the host and port explicitly, as follows:
>>> client = MongoClient('localhost', 27017)
Or use the MongoDB URI format:
>>> client = MongoClient('mongodb://localhost:27017/')
Reference: MongoClient Python Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With