Tuesday, February 14, 2023

PyMongo and MongoDB

PyMongo is a Python library that enables us to connect with MongoDB. It allows us to perform basic operations on the MongoDB database.

So, why Python? It’s a valid question.

We have chosen Python to interact with MongoDB because it is one of the most commonly used and considerably powerful languages for data science. PyMongo allows us to retrieve the data with dictionary-like syntax.

We can also use the dot notation to access MongoDB data. Its easy syntax makes our job a lot easier. Additionally, PyMongo’s rich documentation is always standing there with a helping hand. We will use this library for accessing MongoDB.

MongoDB is available for Linux, Windows and Mac OS X operating systems. Once you have installed the database, you need to start the mongod service. It’s time to fire up your Python notebook and get coding! We have a solid idea of MongoDB – let’s put that knowledge into action.

We will be performing a few key basic operations on a MongoDB database in Python using the PyMongo library.Connecting to the Database

To retrieve the data from a MongoDB database, we will first connect to it. Write and execute the below code in your Jupyter cell in order to connect to MongoDB:

import pymongo 

import pprint

mongo_uri = "mongodb://localhost:27017/"  

client = pymongo.MongoClient(mongo_uri)


Let’s see the available databases:

client.list_database_names()

We will use the sample_analytics database for our purpose. Let’s set the cursor to the same database:

db = client.sample_analytics

The list_collection_names command shows the names of all the available collections:

db.list_collection_names()


Let’s see the number of customers we have. We will connect to the customers collection and then print the number of documents available in that collection:

table=db.customers 

table.count_documents({}) #gives the number of documents in the table

Output: 500

Here, we can see that we have the data for 500 customers. Next, we will fetch a MongoDB document from this table and see what information is present there.




Share:

0 comments:

Post a Comment