-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmongo.py
More file actions
55 lines (50 loc) · 1.99 KB
/
Copy pathmongo.py
File metadata and controls
55 lines (50 loc) · 1.99 KB
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
import pymongo
from bson.objectid import ObjectId
def strs2ObjectIds(id_strings: list):
"""
Converts a list of strings to a set of ObjectIds
"""
output = list()
for id_str in id_strings:
output.append(ObjectId(id_str))
return output
def extractIds(cursor):
ids = list()
for item in cursor:
ids.append(str(item['_id']))
return ids
class MongoAPI:
def __init__(self,
connection_string: str,
):
self.connection = pymongo.MongoClient(connection_string, directConnection=True)
self.db = self.connection.get_database()
async def get_field_data(
self,
collection:str, # MongoDB collection
mongo_ids:list | None, # List of MongoDB ObjectIds as str
field_paths:list, # List of field paths in dotted notation: ['some.example.field1', 'some.other.example.field2']
):
if mongo_ids:
filter = {'_id': {'$in': strs2ObjectIds(mongo_ids)}}
document_count = self.db[collection].count_documents(filter)
cursor = self.db[collection].find(filter, {field_path: True for field_path in field_paths})
else:
document_count = self.db[collection].count_documents({})
cursor = self.db[collection].find({}, {field_path: True for field_path in field_paths})
return document_count, cursor
class Config:
def __init__(self, mongoapi: MongoAPI):
self.mongoapi = mongoapi
self.collection_name = "BioAPI_config"
def get_section(self, section):
return self.mongoapi.db[self.collection_name].find_one({'section':section})
def set_section(self, section: str, config: dict):
return self.mongoapi.db[self.collection_name].replace_one(
{'section': section},
config,
upsert = True)
def load(self, config: dict):
self.mongoapi.db[self.collection_name].insert_many(config)
def clear(self):
self.mongoapi.db[self.collection_name].remove({})