Let us discuss how we are going to export data from Python to Mongo DB. To proceed further we need to have an account in MongoDB. if you don't have you can create one by clicking here.
To connect to database from Python we need a connection string to access our database, follow the below steps to find the string:
- Create an account in MongoDB.com.
- Under Clusters-> Choose Connect.
- After clicking on Connect you will be able to see the below screenshot.
4. Choose Connect to application and select Driver as “Python” & Choose the correct version of Python installed in your system.
5. Copy the link and make sure to replace username and password in the connection string.
Now we are good and we will see the required code to push our data from Python dataframe to Mongo DB.
Open your Jupyter Notebook and run the below code. In the very first step, we will import the required libraries. To integrate Python with MongoDB we have a library called pymongo. If you don't have a pymongo module installed, run the below line to install.
Once you installed import the below libraries.
Now you need to use the connection string with username and password in the below line of code.
Now we need to connect to your database and required collection in MongoDB.
Here replace your database name and collection name.,for example, I am using ‘project’ as my DB name and ‘NewDB’ as my collection name. Make sure to update those details accordingly.
Now we need to convert our data into dictionary format because MongoDB accepts data in JSON format (key, value pairs) that is nothing but Python dictionary. The below line of code converts the dataframe to the dictionary.
Here ‘data’ is my pandas dataframe name, make sure to change it accordingly. data_dict is the dictionary format of our data, now we are all set to upload our data to MongoDB.
This inserts our data into MongoDB, Now you can check your records in your database. Now you should be able to insert data into MongoDB from Python.
Please feel to share or comment if there are any mistakes/queries. I hope you all enjoyed reading this article.