-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongo.py
81 lines (62 loc) · 2.29 KB
/
mongo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# -*- coding: utf-8 -*-
"""
@author: LiaoKong
@time: 2021/08/26 22:00
"""
import pymongo
DB_CONFIG = {
'host': '127.0.0.1',
'port': 27017
}
class Mongo(object):
UP = pymongo.ASCENDING
DOWN = pymongo.DESCENDING
def __init__(self, database_name, collection_name):
self.connect = pymongo.MongoClient(**DB_CONFIG)
self.database = self.connect[database_name]
self.collection = self.database[collection_name]
self._query_data = None
def collection_names(self):
return self.database.list_collection_names()
def add(self, data):
if isinstance(data, dict):
data = [data]
return self.collection.insert_many(data)
def update(self, data, query_filter, upsert=False, multi=True):
return self.collection.update(query_filter, {'$set': data}, upsert,
multi=multi)
def delete(self, query_filter):
if not query_filter:
raise ValueError(
'Query_filter is empty, please user drop_collection delete collection.')
self.collection.delete_many(query_filter)
def drop_collection(self):
return self.collection.drop()
def query_one(self, query_filter, *args, **kwargs):
return self.collection.find_one(query_filter, *args, **kwargs) or {}
def query(self, *args, **kwargs):
self._query_data = self.collection.find(*args, **kwargs)
return self
def all(self, to_list=False):
if to_list:
return list(self._query_data)
return self._query_data
def sort(self, key_or_list):
if self._query_data is None:
raise ValueError('Please try the query function first')
self._query_data = self._query_data.sort(key_or_list)
return self
def limit(self, limit):
if self._query_data is None:
raise ValueError('Please try the query function first')
self._query_data = self._query_data.limit(limit)
return self._query_data
def close(self):
return self.connect.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.connect.close()
if __name__ == '__main__':
with Mongo('FtrackEventsManager', 'EventsInfos') as db:
print(db.collection_names())