Using Python to Operate MongoDB
Using Python to operate the MongoDB database requires the installation of the pymongo library. Pymongo is the official driver for Python to interact with MongoDB, providing various methods and functions to operate MongoDB.
The following is a complete Python code sample that demonstrates how to connect to a MongoDB database and perform data insertion, query, modification, and deletion operations:
python
#Import pymongo library
from pymongo import MongoClient
#Connect to MongoDB database
Client=MongoClient ('localhost ', 27017) # Default connection to local MongoDB server, port number 27017
Db=client ['mydatabase '] # Specify the database to operate on
#Insert Data
Collection=db ['mycollection '] # Specify the collection to operate on
Data={'name ':' John ',' age ': 30,' city ':' New York '} # The data to be inserted
Collection-insert_ One (data) # Insert a piece of data
#Query data
Result=collection. find ({'name ':'John'}) # Query data with name John
for document in result:
print(document)
#Update data
Collection.update_ One ({'name ':'John'}, {$set ': {'age': 35}) # Update the data with name John and change the age to 35
#Delete data
Collection.delete_ One ({'name ':'John'}) # Delete data with name John
#Close Connection
client.close()
The above code first connects to the MongoDB database through the 'MongoClient' class, where 'localhost' is the MongoDB server address and '27017' is the port number. Then specify the database to operate on through the 'client' object and select 'mycollection' as the collection to operate on.
Using 'insert' in code_ The 'one()' method inserts a piece of data. Use the 'find()' method to query data under specified conditions and use 'update'_ The 'one()' method updates the data for the specified condition. Use ` delete_ The 'one()' method deletes data with specified conditions.
Finally, use the 'close()' method to close the connection to MongoDB.
It should be noted that the database name, set name, field name, etc. in the above code can be modified according to the actual situation.