Python与MongoDB交互的方法有多种,以下是常用的几种方法:
示例代码:
from pymongo import MongoClient # 建立数据库连接 client = MongoClient('mongodb://localhost:27017/') # 选择数据库 db = client['mydatabase'] # 选择集合(表) collection = db['mycollection'] # 插入数据 data = {'name': 'John', 'age': 25} collection.insert_one(data) # 查询数据 result = collection.find_one({'name': 'John'}) print(result) # 更新数据 collection.update_one({'name': 'John'}, {'$set': {'age': 26}}) # 删除数据 collection.delete_one({'name': 'John'})
示例代码:
from mongoengine import connect, Document, StringField, IntField # 建立数据库连接 connect('mydatabase') # 定义文档类 class Person(Document): name = StringField() age = IntField() # 创建文档对象 person = Person(name='John', age=25) # 插入数据 person.save() # 查询数据 result = Person.objects(name='John').first() print(result) # 更新数据 Person.objects(name='John').update(set__age=26) # 删除数据 Person.objects(name='John').delete()
示例代码:
import asyncio import motor.motor_asyncio # 建立数据库连接 client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://localhost:27017') # 选择数据库 db = client['mydatabase'] # 选择集合(表) collection = db['mycollection'] # 插入数据 data = {'name': 'John', 'age': 25} await collection.insert_one(data) # 查询数据 result = await collection.find_one({'name': 'John'}) print(result) # 更新数据 await collection.update_one({'name': 'John'}, {'$set': {'age': 26}}) # 删除数据 await collection.delete_one({'name': 'John'})
这些是常用的Python与MongoDB交互的方法,根据项目的需求和各自的编程习惯可以选择合适的方法。