用PYTHON 写一个类,可以进行MONGO数据库的增删改查,包含分页查询
时间: 2023-02-05 15:30:24 浏览: 163
这是一个简单的例子,你可以使用它来了解如何在 Python 中使用类来进行 MongoDB 数据库的增删改查操作,包括分页查询:
```python
from pymongo import MongoClient
class MongoDB:
def __init__(self, host, port, database, collection):
self.client = MongoClient(host, port)
self.db = self.client[database]
self.collection = self.db[collection]
def insert_one(self, document):
self.collection.insert_one(document)
def insert_many(self, documents):
self.collection.insert_many(documents)
def find_one(self, filter):
return self.collection.find_one(filter)
def find_many(self, filter, page, size):
return self.collection.find(filter).skip((page - 1) * size).limit(size)
def update_one(self, filter, update):
self.collection.update_one(filter, update)
def update_many(self, filter, update):
self.collection.update_many(filter, update)
def delete_one(self, filter):
self.collection.delete_one(filter)
def delete_many(self, filter):
self.collection.delete_many(filter)
```
你可以像这样使用这个类:
```python
# 创建 MongoDB 实例
mongodb = MongoDB('localhost', 27017, 'test', 'users')
# 插入一个文档
document = {'name': 'Alice', 'age': 25}
mongodb.insert_one(document)
# 插入多个文档
documents = [{'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 35}]
mongodb.insert_many(documents)
# 查询一个文档
filter = {'name': 'Alice'}
alice = mongodb.find_one(filter)
print(alice)
# 查询多个文档(分页)
filter = {}
page = 1
size = 2
users = mongodb.find_many(filter, page, size)
for user in users:
print(user)
# 更新一个文档
filter = {'name': 'Alice'}
update = {'$set': {'age': 26}}
mongodb.update_one(filter, update)
# 更新多个文档
filter = {'age': {'$lt': 30}}
update = {
阅读全文