To use MongoDB from within Python we will be using the PyMongo Library. PyMongo contains tools that helps you to work with MongoDB. There are libraries that act as an object data mapper for MongoDB, however PyMongo is the recommended one.
To install PyMongo, you can run the following:
python -m pip install pymongo
Alternatively, you can use the following:
import sys
!{sys.executable} -m pip install pymongo
Finally, you can get started with using MongoDB by importing the PyMongo library and then setting up a connection with MongoDB, as shown in the following code:
import pymongo
connection = pymongo.MongoClient()
On creating a successful connection with MongoDB, you can continue with different operations, like listing the databases present and so on, as seen in the following argument:
connection.database_names() #list databases in MongoDB
Each database in MongoDB contains data in containers called collections. You can retrieve data from these collections to pursue your desired operation, as follows:
selected_DB = connection["database_name"] selected_DB.collection_names() # list all collections within the selected database