实现一个MONGO工具类
时间: 2023-02-06 22:27:36 浏览: 70
好的,这是一个示例的 MongoDB 工具类的实现:
```
import pymongo
class MongoDBUtil:
def __init__(self, host, port, db_name):
self.client = pymongo.MongoClient(host, port)
self.db = self.client[db_name]
def insert_one(self, collection, data):
"""插入一条数据"""
self.db[collection].insert_one(data)
def insert_many(self, collection, data_list):
"""插入多条数据"""
self.db[collection].insert_many(data_list)
def find_one(self, collection, query={}):
"""查找一条数据"""
return self.db[collection].find_one(query)
def find(self, collection, query={}):
"""查找多条数据"""
return self.db[collection].find(query)
def update_one(self, collection, query, update):
"""更新一条数据"""
self.db[collection].update_one(query, update)
def update_many(self, collection, query, update):
"""更新多条数据"""
self.db[collection].update_many(query, update)
def delete_one(self, collection, query):
"""删除一条数据"""
self.db[collection].delete_one(query)
def delete_many(self, collection, query):
"""删除多条数据"""
self.db[collection].delete_many(query)
```
使用这个工具类时,需要先实例化一个对象,然后调用相应的方法即可完成对 MongoDB 数据库的操作。
例如,如果要插入一条数据,可以这样调用:
```
util = MongoDBUtil('localhost', 27017, 'mydb')
util.insert_one('users', {'name': 'John', 'age': 30})
```
这样就能在 `mydb` 数据库的 `users` 集合中插入一条名为 John,年龄为 30 的数据了。
请注意,这只是一个示例,实