pymongo 使用
程序员文章站
2022-05-28 17:06:34
...
# @Time : 2019/11/30 18:06
# @Author : GKL
# FileName : mongodb去重.py
# Software : PyCharm
import pymongo
# 去重异常捕获
from pymongo.errors import DuplicateKeyError
class MongoDb(object):
def __init__(self):
self.client = pymongo.MongoClient()
self.db = self.client['proxy']
self.collection = self.db['proxy']
# 去重操作(通过ip去重)
self.collection.ensure_index('ip', unique=True)
def insert(self, data):
try:
self.collection.insert_one(data)
except DuplicateKeyError as e:
print(e)
def delete(self, conditions):
result = self.collection.remove(conditions)
if result['n'] == 1:
print(f'删除成功:{conditions}')
return True
elif result['n'] == 0:
print(f'删除失败:{conditions}')
return False
def update(self, conditions, value):
self.collection.update(conditions, {"$set": value})
print(f'更新{conditions}的数据为{value}')
def get(self, count):
count = int(count)
items = self.collection.find({}, limit=count).sort(
'delay', pymongo.ASCENDING
)
items = [{'ip': i['ip']} for i in items]
return items
def get_count(self, conditions=None):
conditions = {} if conditions is None else conditions
return self.collection.count(conditions)
if __name__ == '__main__':
data = {
'name': "python",
'age': 18
}
s = MongoDb()
s.insert(data)
上一篇: struts2自定义拦截器
下一篇: pymongo的使用