Python MongoDB



 

Getting Started with Python and MongoDB

MongoDB is a popular NoSQL database, and you can interact with it using Python by using the pymongo library. Below is a guide on how to get started with MongoDB using Python.


1. Prerequisites

Ensure you have:

  • MongoDB installed and running on your machine or accessible via the cloud (e.g., MongoDB Atlas).
  • The pymongo library installed. You can install it via pip:
bash
pip install pymongo

2. Importing the Required Libraries

Start by importing pymongo to interact with MongoDB:

python
import pymongo
from pymongo import MongoClient

3. Connecting to MongoDB

You can connect to a local MongoDB instance using the default connection string:

python
client = MongoClient("mongodb://localhost:27017/")

To connect to a cloud-based MongoDB instance, use your MongoDB URI:

python
client = MongoClient("your_mongodb_atlas_uri")

4. Creating or Accessing a Database

MongoDB automatically creates a database if it doesn’t already exist. Access a database using:

python
db = client["mydatabase"]

5. Creating or Accessing a Collection

Collections are like tables in a relational database. You can access or create one like this:

python
collection = db["customers"]

6. Inserting Documents

To insert one document:

python
customer = { "name": "John", "address": "Highway 37" }
collection.insert_one(customer)

To insert multiple documents at once:

python
customers = [
  { "name": "Amy", "address": "Apple st 652" },
  { "name": "Michael", "address": "Valley 345" },
]
collection.insert_many(customers)

7. Querying the Database

To query the collection:

python
query = { "name": "John" }
result = collection.find(query)
for customer in result:
    print(customer)

If you want to get all documents:

python
result = collection.find()
for customer in result:
    print(customer)

8. Updating Documents

To update an existing document:

python
query = { "name": "John" }
new_values = { "$set": { "address": "Canyon 123" } }
collection.update_one(query, new_values)

9. Deleting Documents

To delete one document:

python
query = { "name": "John" }
collection.delete_one(query)

To delete all documents matching a query:

python
query = { "address": { "$regex": "^S" } }
collection.delete_many(query)

Conclusion

In this guide, you learned how to:

  1. Connect to a MongoDB database using Python.
  2. Insert, query, update, and delete documents in MongoDB collections.