Python and MongoDB are usually implemented through the pymongo library. pymongo is an official Python driver for interacting with MongoDB databases. Here is a simple example showing how to use pymongo to connect to a MongoDB database and perform some basic database operations (such as inserting, querying, updating, and deleting documents).
Install pymongo
pip install pymongo
Python connection to Mongodb
from pymongo import MongoClient # Create a MongoClient object that is used to connect to the Mongodb database serverclient = MongoClient('mongodb://admin:password@localhost:27017/')
Add data to the database
from mongo_db import client # .insert_one({"name": "Luna"}) # .insert_many([{"name":"Lanling King"}, {"name": "Baili Xuance"}]) ({})
Query data
from mongo_db import client try: teachers = () # print(teachers) for one in teachers: print(one["_id"],one["name"]) # Conditional query teacher = .find_one({"name":"Lanling King"}) print(teacher["_id"],teacher["name"]) except Exception as e: print(e)
Update and modify data
from mongo_db import client try: # Change the entire table. If there is no column in the table, this column will be added. # .update_many({}, {'$set': {"role":["Class Teacher"]}}) # .update_one({"name": "Luna"},{"$set":{"sex": "Female"}}) # push append (list) .update_one({"name": "Luna"},{"$push":{"role": "Class Director Wang"}}) except Exception as e: print(e)
Delete data
from mongo_db import client try: # Conditional query # .delete_one({"name": "Luna"}) # Delete multiple data .delete_many({}) except Exception as e: print(e)
Index
Create indexes to optimize query performance.
collection.create_index([("name", )])
Aggregation framework
Complex data aggregation operations using an aggregation framework
pipeline = [ {"$match": {"age": {"$gt": 25}}}, {"$group": {"_id": "$city", "count": {"$sum": 1}}} ] results = (pipeline) for result in results: print(result)
Affairs
Starting with MongoDB 4.0, it supports multi-document transactions to ensure data consistency and integrity.
with client.start_session() as session: with session.start_transaction(): collection.update_one({"name": "John"}, {"$set": {"age": 32}}, session=session) collection.update_one({"name": "Alice"}, {"$set": {"age": 26}}, session=session) session.commit_transaction()
Close the connection
()
Things to note
When using pymongo for MongoDB operations, you need to make sure that the MongoDB service has been started and the network connection is normal.
When performing data insertion, update and delete operations, you need to pay attention to the integrity and consistency of the data.
MongoDB's collection is created dynamically, that is, when data is inserted into a non-existent collection, MongoDB will automatically create the collection.
This is the introduction to this article about the code implementation of Python and MongoDB interaction. For more related content on Python and MongoDB interaction, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!