Python MongoDB Connectivity
MongoDB is a popular open-source NoSQL database that is widely used for storing and retrieving data in a flexible, scalable, and document-oriented manner. It provides a rich set of features and functionalities for managing and manipulating data.
To work with MongoDB in Python, you need to install the pymongo package, which is the official Python driver for MongoDB. You can install it using the following command:
pip install pymongo
Once you have installed the pymongo package, you can establish a connection to a MongoDB server and perform various operations such as creating databases, inserting documents, querying data, updating documents, and deleting documents.
Here's a simple example that demonstrates some basic MongoDB operations using Python:
from pymongo import MongoClient
# Establish a connection to the MongoDB server
client = MongoClient('mongodb://localhost:27017/')
# Access a specific database
db = client['mydatabase']
# Access a specific collection (similar to a table in relational databases)
collection = db['mycollection']
# Insert a document into the collection
document = {"name": "John", "age": 30, "city": "New York"}
collection.insert_one(document)
# Query data from the collection
result = collection.find({"name": "John"})
for document in result:
print(document)
# Update a document in the collection
collection.update_one({"name": "John"}, {"$set": {"age": 31}})
# Delete a document from the collection
collection.delete_one({"name": "John"})
# Close the connection
client.close()
In the above code, we establish a connection to the MongoDB server running on localhost at the default port 27017. We access a specific database named mydatabase and a collection (similar to a table) named mycollection. We then perform operations such as inserting a document, querying data, updating a document, and deleting a document.
The pymongo package provides a comprehensive API for interacting with MongoDB, including advanced querying, indexing, aggregation, and more. You can refer to the official documentation of pymongo for detailed information on using the package and performing specific operations with MongoDB in Python.