|
|
|
@@ -27,7 +27,7 @@ import logging
|
|
|
|
|
from typing import Any, List, Optional
|
|
|
|
|
|
|
|
|
|
from pymongo import ReturnDocument
|
|
|
|
|
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorCollection
|
|
|
|
|
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorCollection, AsyncIOMotorDatabase
|
|
|
|
|
|
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
@@ -48,7 +48,7 @@ class Mongo:
|
|
|
|
|
return self._db[name]
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def database(self):
|
|
|
|
|
def database(self) -> AsyncIOMotorDatabase:
|
|
|
|
|
"""raw motor database handle"""
|
|
|
|
|
return self._db
|
|
|
|
|
|
|
|
|
@@ -181,7 +181,11 @@ class Mongo:
|
|
|
|
|
return []
|
|
|
|
|
|
|
|
|
|
async def get_document_hashmap(self, collection: str, target: dict, key: str) -> dict:
|
|
|
|
|
"""return matching documents keyed into a dict by the given field"""
|
|
|
|
|
"""return matching documents keyed into a dict by the given field
|
|
|
|
|
|
|
|
|
|
documents missing `key` are skipped (not in the result); a later document
|
|
|
|
|
with a duplicate key value overwrites an earlier one.
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
cursor = self._db[collection].find(target)
|
|
|
|
|
return {doc[key]: doc async for doc in cursor if key in doc}
|
|
|
|
@@ -192,7 +196,11 @@ class Mongo:
|
|
|
|
|
async def get_document_fields(
|
|
|
|
|
self, collection: str, target: dict, key: str, fields: Optional[dict] = None
|
|
|
|
|
) -> List:
|
|
|
|
|
"""return a flat list of one field's value across matching documents"""
|
|
|
|
|
"""return a flat list of one field's value across matching documents
|
|
|
|
|
|
|
|
|
|
documents missing `key` are skipped, so the list length may be smaller than
|
|
|
|
|
the match count.
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
cursor = self._db[collection].find(target, fields)
|
|
|
|
|
return [doc[key] async for doc in cursor if key in doc]
|
|
|
|
@@ -208,6 +216,14 @@ class Mongo:
|
|
|
|
|
log.exception(f"db.count_documents() on {collection}")
|
|
|
|
|
return 0
|
|
|
|
|
|
|
|
|
|
async def check_document_exists(self, collection: str, target: dict) -> bool:
|
|
|
|
|
"""return whether at least one document in collection matches target"""
|
|
|
|
|
try:
|
|
|
|
|
return await self._db[collection].count_documents(target, limit=1) > 0
|
|
|
|
|
except Exception:
|
|
|
|
|
log.exception(f"db.check_document_exists() on {collection}")
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
async def count_value_in_array(self, collection: str, array_field: str, value: str) -> int:
|
|
|
|
|
"""count documents whose array field contains value"""
|
|
|
|
|
try:
|
|
|
|
@@ -271,11 +287,11 @@ class Mongo:
|
|
|
|
|
# update
|
|
|
|
|
|
|
|
|
|
async def update_document(
|
|
|
|
|
self, collection: str, target: dict, document: dict, do_upsert: bool = False
|
|
|
|
|
self, collection: str, target: dict, document: dict, upsert: bool = False
|
|
|
|
|
) -> bool:
|
|
|
|
|
"""replace a whole document, optionally upserting"""
|
|
|
|
|
try:
|
|
|
|
|
response = await self._db[collection].replace_one(target, document, upsert=do_upsert)
|
|
|
|
|
response = await self._db[collection].replace_one(target, document, upsert=upsert)
|
|
|
|
|
return bool(response.matched_count or response.upserted_id)
|
|
|
|
|
except Exception:
|
|
|
|
|
log.exception(f"db.update_document() on {collection}")
|
|
|
|
@@ -291,10 +307,15 @@ class Mongo:
|
|
|
|
|
return 0
|
|
|
|
|
|
|
|
|
|
async def update_document_field(self, collection: str, target: dict, updates: dict) -> bool:
|
|
|
|
|
"""$set one or more fields on a single document"""
|
|
|
|
|
"""$set one or more fields on a single document
|
|
|
|
|
|
|
|
|
|
returns True when a document matched, even if the write changed nothing (a
|
|
|
|
|
`$set` to the identical value leaves `modified_count=0`); use `matched_count`
|
|
|
|
|
so an idempotent no-op on an existing doc isn't misread as a failure.
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
response = await self._db[collection].update_one(target, {"$set": updates})
|
|
|
|
|
return response.modified_count > 0
|
|
|
|
|
return response.matched_count > 0
|
|
|
|
|
except Exception:
|
|
|
|
|
log.exception(f"db.update_document_field() on {collection}")
|
|
|
|
|
return False
|
|
|
|
@@ -302,10 +323,15 @@ class Mongo:
|
|
|
|
|
async def update_document_operator(
|
|
|
|
|
self, collection: str, target: dict, update_query: dict
|
|
|
|
|
) -> bool:
|
|
|
|
|
"""apply raw update operators ($set/$inc/$unset/...) to a single document"""
|
|
|
|
|
"""apply raw update operators ($set/$inc/$unset/...) to a single document
|
|
|
|
|
|
|
|
|
|
returns True when a document matched, even if the operators changed nothing
|
|
|
|
|
(e.g. `$set` to an identical value) — use `matched_count` so an idempotent
|
|
|
|
|
write on an existing doc isn't misread as a failure.
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
response = await self._db[collection].update_one(target, update_query)
|
|
|
|
|
return response.modified_count > 0
|
|
|
|
|
return response.matched_count > 0
|
|
|
|
|
except Exception:
|
|
|
|
|
log.exception(f"db.update_document_operator() on {collection}")
|
|
|
|
|
return False
|
|
|
|
@@ -335,10 +361,15 @@ class Mongo:
|
|
|
|
|
async def document_push_array(
|
|
|
|
|
self, collection: str, target: dict, array: str, value: Any
|
|
|
|
|
) -> bool:
|
|
|
|
|
"""$push a value onto an array field"""
|
|
|
|
|
"""$push a value onto an array field
|
|
|
|
|
|
|
|
|
|
returns True when a document matched (consistent with the other single-doc
|
|
|
|
|
update helpers); $push always mutates, so matched_count and modified_count
|
|
|
|
|
agree here in practice.
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
response = await self._db[collection].update_one(target, {"$push": {array: value}})
|
|
|
|
|
return response.modified_count > 0
|
|
|
|
|
return response.matched_count > 0
|
|
|
|
|
except Exception:
|
|
|
|
|
log.exception(f"db.document_push_array() on {collection}")
|
|
|
|
|
return False
|
|
|
|
@@ -347,13 +378,17 @@ class Mongo:
|
|
|
|
|
self, collection: str, target: dict, array: str, value: Any,
|
|
|
|
|
field_to_set: str, set_value: Any,
|
|
|
|
|
) -> bool:
|
|
|
|
|
"""$push to an array and $set a field in one update"""
|
|
|
|
|
"""$push to an array and $set a field in one update
|
|
|
|
|
|
|
|
|
|
returns True when a document matched (consistent with the other single-doc
|
|
|
|
|
update helpers).
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
response = await self._db[collection].update_one(
|
|
|
|
|
target,
|
|
|
|
|
{"$push": {array: value}, "$set": {field_to_set: set_value}},
|
|
|
|
|
)
|
|
|
|
|
return response.modified_count > 0
|
|
|
|
|
return response.matched_count > 0
|
|
|
|
|
except Exception:
|
|
|
|
|
log.exception(f"db.document_push_and_set() on {collection}")
|
|
|
|
|
return False
|
|
|
|
@@ -361,24 +396,29 @@ class Mongo:
|
|
|
|
|
async def document_pop_array(
|
|
|
|
|
self, collection: str, target: dict, array: str, value: Any
|
|
|
|
|
) -> bool:
|
|
|
|
|
"""$pull a value from an array field"""
|
|
|
|
|
"""$pull a value from an array field
|
|
|
|
|
|
|
|
|
|
returns True when a document matched, even if nothing was pulled (the value
|
|
|
|
|
was absent) — use `matched_count` so a no-op pull on an existing doc isn't
|
|
|
|
|
misread as a failure.
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
response = await self._db[collection].update_one(target, {"$pull": {array: value}})
|
|
|
|
|
return response.modified_count > 0
|
|
|
|
|
return response.matched_count > 0
|
|
|
|
|
except Exception:
|
|
|
|
|
log.exception(f"db.document_pop_array() on {collection}")
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
async def find_one_and_update(
|
|
|
|
|
self, collection: str, target: dict, update: dict,
|
|
|
|
|
return_after: bool = True, do_upsert: bool = False, fields: Optional[dict] = None,
|
|
|
|
|
return_after: bool = True, upsert: bool = False, fields: Optional[dict] = None,
|
|
|
|
|
) -> Optional[dict]:
|
|
|
|
|
"""atomically update one doc and return it (after-image by default)"""
|
|
|
|
|
try:
|
|
|
|
|
return await self._db[collection].find_one_and_update(
|
|
|
|
|
target, update,
|
|
|
|
|
projection=fields,
|
|
|
|
|
upsert=do_upsert,
|
|
|
|
|
upsert=upsert,
|
|
|
|
|
return_document=ReturnDocument.AFTER if return_after else ReturnDocument.BEFORE,
|
|
|
|
|
)
|
|
|
|
|
except Exception:
|
|
|
|
@@ -387,14 +427,14 @@ class Mongo:
|
|
|
|
|
|
|
|
|
|
async def find_one_and_replace(
|
|
|
|
|
self, collection: str, target: dict, document: dict,
|
|
|
|
|
return_after: bool = True, do_upsert: bool = False, fields: Optional[dict] = None,
|
|
|
|
|
return_after: bool = True, upsert: bool = False, fields: Optional[dict] = None,
|
|
|
|
|
) -> Optional[dict]:
|
|
|
|
|
"""atomically replace one doc and return it (after-image by default)"""
|
|
|
|
|
try:
|
|
|
|
|
return await self._db[collection].find_one_and_replace(
|
|
|
|
|
target, document,
|
|
|
|
|
projection=fields,
|
|
|
|
|
upsert=do_upsert,
|
|
|
|
|
upsert=upsert,
|
|
|
|
|
return_document=ReturnDocument.AFTER if return_after else ReturnDocument.BEFORE,
|
|
|
|
|
)
|
|
|
|
|
except Exception:
|
|
|
|
|