Python MongoDB

Python MongoDB

Python is a widely used high-level interpreted language, known for its ease of use and readability. MongoDB is a powerful document-oriented database system that is well-suited for storing data in JSON format.

In this blog post, we’ll show how to use Python and MongoDB to store and query data in JSON format. We’ll also cover some best practices for working with MongoDB from Python.

Install and setup

First, we’ll need to install the Python MongoDB driver. The easiest way to do this is using pip:

pip install pymongo

Next, we’ll need to connect to our MongoDB database. We’ll do this using the MongoClient class:

from pymongo import MongoClient

client = MongoClient('localhost', 27017)

Once we have a MongoClient instance, we can access our database using the database name:

db = client.test_database

We can then access our collection using the collection name:

collection = db.test _collection

Now that we have a reference to our collection, we can insert data into it. We’ll use the insert_one() method to insert a document into our collection:

result = collection.insert_one({'name': 'Test User'})

print('Inserted document with ID {}'.format(result.inserted_id))

We can also insert multiple documents into our collection using the insert_many() method:

result = collection.insert_many([
    {'name': 'Test User 1'},
    {'name': 'Test User 2'}
])

print('Inserted {} documents'.format(len(result.inserted_ids)))

If we want to query our collection, we can use the find() method. This method returns a Cursor instance, which allows us to iterate over the results:

for document in collection.find():
    print(document) We can also query for specific documents using the find() method:

for document in collection.find({'name': 'Test User 1'}):
    print(document)

We can also use the find_one() method to query for a single document:

document = collection.find_one({'name': 'Test User'})

print(document)

If we want to update a document, we can use the update_one() method:

result = collection.update_one(
    {'name': 'Test User'},
    {'$set': {'name': 'Updated Test User'}}
)

print('Updated {} document'.format(result.matched_count))

We can also update multiple documents using the update_many() method:

result = collection.update_many(
    {'name': 'Test User'},
    {'$set': {'name': 'Updated Test User'}}
)

print('Updated {} documents'.format(result.matched_count))

Finally, we can delete documents from our collection using the delete_one() and delete_many() methods:

result = collection.delete_one({'name': 'Updated Test User'})

print('Deleted {} document'.format(result.deleted_count))

result = collection.delete_ many({'name': 'Updated Test User'})

print('Deleted {} documents'.format(result.deleted_count))

That’s all there is to working with MongoDB from Python!

Leave a Reply