Introduction:

In the world of database management, MongoDB stands out as a popular NoSQL database, offering flexibility and scalability. Python developers can leverage the PyMongo library to interact seamlessly with MongoDB databases. In this article, we’ll explore the fundamental operations provided by PyMongo using a practical example. We’ll cover connecting to MongoDB, inserting documents, querying data, updating records, and more.

Setting Up PyMongo:

Before diving into PyMongo operations, ensure that you have PyMongo installed. You can install it using the following command:

pip install pymongo

Connecting to MongoDB:

To get started, establish a connection to your MongoDB server. In the provided Python code snippet, we use MongoClient to connect to a local MongoDB instance on the default port:

from pymongo import MongoClient

client = MongoClient('localhost', 27017)

Selecting a Database and Collection:

Once connected, specify the database and collection you want to work with. In our example, we select the “feat” database and two collections: “featurepreneurs” and “employers”:

db = client['feat']
featurepreneur_collection = db['featurepreneurs']
employer_collection = db['employers']

Inserting Documents:

Use the insert_one method to insert a document into a collection. The example below inserts a user's details into the "featurepreneurs" collection:

uid = 18006

def insert_user_details(username, password):
featurepreneur_dict = {'uid': uid, 'username': username, 'password': password}
featurepreneur_collection.insert_one(featurepreneur_dict)
uid += 1

Querying Documents:

Retrieve documents from a collection using various query methods. The provided code demonstrates querying all documents, excluding the “uid” field:

for uid in featurepreneur_collection.find({}, {"uid": 0}):
print(uid)

Sorting Documents:

Sort documents in ascending or descending order based on a specific field. The following code sorts documents in descending order based on the “username” field:

fdoc = featurepreneur_collection.find().sort("username", -1)

for doc in fdoc:
print(doc)

Deleting Documents:

Remove documents from a collection using the delete_one method. The example deletes a document with the username "mohammed" from the "featurepreneurs" collection:

feat_query = {'username': 'mohammed'}
featurepreneur_collection.delete_one(feat_query)

Conclusion:

PyMongo simplifies MongoDB interactions in Python, providing a comprehensive set of methods for database operations. In this article, we covered connecting to MongoDB, inserting and querying documents, sorting, and deleting records. As you explore PyMongo further, you’ll discover additional features and advanced functionalities to streamline your MongoDB-driven applications.

Happy coding with PyMongo and MongoDB!

--

--