Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pymongo: MongoClient or Connection

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?

like image 473
icn Avatar asked Dec 19 '12 19:12

icn


People also ask

How to connect to MongoDB using pymongo?

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 “.

What is pymongo client?

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.

What is mongoclient in MongoDB?

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.

How do I install pymongo on Python 3?

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.


2 Answers

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.

like image 56
sean Avatar answered Oct 09 '22 00:10

sean


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

like image 6
muruga Avatar answered Oct 09 '22 01:10

muruga