Python MongoDB Get Started

To get started with Python and MongoDB, you’ll need to use the pymongo library, which allows Python to interact with a MongoDB database.

Here’s a step-by-step guide on how to set up and use MongoDB with Python.

1. Install MongoDB and PyMongo

Install MongoDB

First, you need to install MongoDB on your system. You can download it from the official website: MongoDB Download.

Install pymongo in Python

You can install pymongo using pip:

pip install pymongo

2. Connect to MongoDB

Once you have MongoDB installed and running, you can connect to it using pymongo in Python.

Example of Connecting to a MongoDB Server

import pymongo

# Connect to MongoDB server
client = pymongo.MongoClient("mongodb://localhost:27017/")

# Check if the connection was successful
print(client.list_database_names())

This code connects to the MongoDB server running on localhost (your local machine) and prints the list of databases available.

3. Create or Access a Database

In MongoDB, databases are created when you first store data in them. To access or create a database:

# Access a database (creates it if it doesn't exist)
mydb = client["mydatabase"]

# List all databases
print(client.list_database_names())

If the database doesn’t exist, MongoDB will create it when you add data.

4. Create or Access a Collection

A collection in MongoDB is similar to a table in a relational database. You can create or access a collection within the database:

# Access a collection (creates it if it doesn't exist)
mycol = mydb["customers"]

# List all collections
print(mydb.list_collection_names())

Again, the collection is created when you insert data into it.

5. Insert Data into MongoDB

You can insert data into a collection by using insert_one() or insert_many() methods.

Insert a Single Document

A document in MongoDB is similar to a row in a relational database.

# Example document (record) to insert
mydict = { "name": "John", "address": "123 Elm Street" }

# Insert a single document
x = mycol.insert_one(mydict)

# Output the inserted document's ID
print(x.inserted_id)

Insert Multiple Documents

You can insert multiple documents at once using insert_many():

# List of documents to insert
mylist = [
  { "name": "Amy", "address": "456 Oak Street" },
  { "name": "Mark", "address": "789 Maple Avenue" },
  { "name": "Sara", "address": "101 Pine Road" }
]

# Insert multiple documents
x = mycol.insert_many(mylist)

# Output the inserted document's IDs
print(x.inserted_ids)

6. Query Data from MongoDB

You can retrieve data from MongoDB using the find() method. To fetch all documents from a collection:

# Retrieve all documents in the collection
for doc in mycol.find():
    print(doc)

Query with a Filter

You can also query documents based on certain conditions using a filter:

# Find a document where the name is "John"
query = { "name": "John" }

# Retrieve the matching document
result = mycol.find(query)

for doc in result:
    print(doc)

7. Update Documents

To update a document, use the update_one() or update_many() methods.

Update a Single Document

# Update the address of the document where the name is "John"
query = { "name": "John" }
new_values = { "$set": { "address": "500 New Address" } }

# Perform the update
mycol.update_one(query, new_values)

Update Multiple Documents

# Update the address of all documents where the name is "Amy"
query = { "name": "Amy" }
new_values = { "$set": { "address": "789 New Address" } }

# Perform the update
mycol.update_many(query, new_values)

8. Delete Documents

To delete documents, you can use the delete_one() or delete_many() methods.

Delete a Single Document

# Delete the document where the name is "John"
query = { "name": "John" }

mycol.delete_one(query)

Delete Multiple Documents

# Delete all documents where the address starts with "789"
query = { "address": { "$regex": "^789" } }

mycol.delete_many(query)

9. Drop a Collection

If you want to delete an entire collection, you can use the drop() method:

# Drop the entire collection
mycol.drop()

print("Collection dropped.")

10. Full Example: Connecting to MongoDB and Performing Operations

import pymongo

# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")

# Access or create a database
mydb = client["mydatabase"]

# Access or create a collection
mycol = mydb["customers"]

# Insert multiple documents
mylist = [
  { "name": "Amy", "address": "456 Oak Street" },
  { "name": "Mark", "address": "789 Maple Avenue" },
  { "name": "Sara", "address": "101 Pine Road" }
]
mycol.insert_many(mylist)

# Query the collection
for doc in mycol.find():
    print(doc)

# Update a document
query = { "name": "Amy" }
new_values = { "$set": { "address": "Updated Address" } }
mycol.update_one(query, new_values)

# Delete a document
mycol.delete_one({ "name": "Mark" })

# Drop the collection
mycol.drop()

Summary:

  • Use pymongo to connect Python to a MongoDB database.
  • You can perform standard database operations such as insert, update, delete, and query.
  • MongoDB documents are flexible and stored in collections, which are similar to tables in relational databases.
Leave a Reply 0

Your email address will not be published. Required fields are marked *