Class ObservationRepository
- Namespace
- adas_core.Infrastructure.Repositories
- Assembly
- adas-core.Infrastructure.dll
Repository implementation for managing PatientObservation entities in MongoDB. Provides specialized query, aggregation, retention, and expiration operations for patient clinical observations.
public class ObservationRepository : MongoRepository<PatientObservation>, IObservationRepository, IMongoRepository<PatientObservation>
- Inheritance
-
ObservationRepository
- Implements
- Inherited Members
- Extension Methods
Constructors
ObservationRepository(IOptions<ApiSettings>?, IMongoDatabase, ILogger<ObservationRepository>)
Initializes a new instance of the ObservationRepository class.
public ObservationRepository(IOptions<ApiSettings>? apiSettings, IMongoDatabase database, ILogger<ObservationRepository> logger)
Parameters
apiSettingsIOptions<ApiSettings>The application API settings containing configuration values, including the collection name. Must not be null.
databaseIMongoDatabaseThe MongoDB database instance used to access the collection.
loggerILogger<ObservationRepository>The logger used to record diagnostic and error information.
Exceptions
- ArgumentNullException
Thrown when
apiSettingsis null.
Methods
AggregatedPatientActiveIntravenousLinesObservations(ObjectId)
Asynchronously retrieves the currently active intravenous-line observations for a patient,
grouping by the Location and Type of the PatientIntravenousLinesValue.
Within each group, only the most recent observation (ordered by time and id) is returned.
public Task<List<PatientObservation?>> AggregatedPatientActiveIntravenousLinesObservations(ObjectId patientId)
Parameters
patientIdObjectIdThe unique identifier of the patient.
Returns
- Task<List<PatientObservation>>
A List<T> containing one observation per unique (Location, Type) combination.
AggregatedPatientGroupedObservations(ObjectId, GroupedField)
Asynchronously executes an aggregation pipeline that groups a patient's observations into time buckets (second / minute / hour / day / shift / times) and computes per-bucket results such as first, last, min, max, sum, average, or count. Supports a "since last observation" mode and a configurable look-back window based on the regularity.
public Task<List<BsonDocument>> AggregatedPatientGroupedObservations(ObjectId patientId, GroupedField groupedField)
Parameters
patientIdObjectIdThe unique identifier of the patient.
groupedFieldGroupedFieldA GroupedField descriptor containing the observation name(s), regularity, look-back window, and the result computations to perform.
Returns
- Task<List<BsonDocument>>
A List<T> with one document per time bucket. Returns an empty list when an exception occurs while executing the pipeline.
AggregatedPatientLastObservations(ObjectId, int, List<string>?)
Asynchronously retrieves the most recent observations for a patient, optionally restricted to a list of observation names.
If filterObservations is null, all distinct observation names for the patient are used.
public Task<List<PatientObservation>> AggregatedPatientLastObservations(ObjectId patientId, int num, List<string>? filterObservations = null)
Parameters
patientIdObjectIdThe unique identifier of the patient.
numintThe maximum number of observations to return per observation name.
filterObservationsList<string>Optional list of observation names to restrict the query to. When null, all distinct names are discovered.
Returns
- Task<List<PatientObservation>>
A List<T> containing the aggregated latest observations across all matching names.
AggregatedPatientLastObservationsByField(ObjectId, List<Field>?)
Asynchronously retrieves the most recent observations for a patient, with per-field limits and an optional "expired" flag filter.
When a Field specifies OnlyExpired as true, only expired observations are returned.
When filterObservations is null, all observations for the patient are returned.
public Task<List<PatientObservation>> AggregatedPatientLastObservationsByField(ObjectId patientId, List<Field>? filterObservations)
Parameters
patientIdObjectIdThe unique identifier of the patient.
filterObservationsList<Field>Optional list of Field descriptors defining the names, limits, and expiration filter. When null, all observations for the patient are returned.
Returns
- Task<List<PatientObservation>>
A List<T> containing the matching observations. Returns an empty list when an exception occurs while querying the database.
AggregatedPatientLastObservationsByLastDate(ObjectId, int, DateTime, List<string>?)
Asynchronously retrieves the most recent observations for a patient that occurred on or before a given date, optionally restricted to a list of observation names.
public Task<List<PatientObservation>> AggregatedPatientLastObservationsByLastDate(ObjectId patientId, int num, DateTime lastDate, List<string>? filterObservations = null)
Parameters
patientIdObjectIdThe unique identifier of the patient.
numintThe maximum number of observations to return per observation name.
lastDateDateTimeThe inclusive upper bound (UTC) for the observation
timefield.filterObservationsList<string>Optional list of observation names to restrict the query to. When null, all distinct names are discovered.
Returns
- Task<List<PatientObservation>>
A List<T> containing the matching observations.
CreateIndexes()
Creates the indexes required by the observations collection to support the repository's query patterns. Indexes are created in the background and are non-unique. If an error occurs, it is logged and rethrown.
public override Task CreateIndexes()
Returns
Exceptions
- Exception
Rethrown when an error occurs while creating the indexes.
DeleteAsync(ObjectId)
Asynchronously deletes a single observation by its identifier. This method hides the base
DeleteAsync(ObjectId) defined on MongoRepository<T> because the base returns the deleted document,
while this implementation is fire-and-forget.
public Task DeleteAsync(ObjectId id)
Parameters
idObjectIdThe MongoDB.Bson.ObjectId of the observation to delete.
Returns
DeleteByPatientId(ObjectId)
Asynchronously deletes all observations associated with the specified patient.
public Task DeleteByPatientId(ObjectId id)
Parameters
idObjectIdThe MongoDB.Bson.ObjectId of the patient whose observations should be removed.
Returns
DeleteOlderDaysAsync(string, int)
Deletes all observations with the specified name that are older than the configured number of days. Returns the documents that were deleted for downstream processing.
public Task<List<PatientObservation>> DeleteOlderDaysAsync(string name, int retentionPolicyValue)
Parameters
namestringThe observation name to filter by.
retentionPolicyValueintThe retention window expressed in days. Observations older than
UtcNow - retentionPolicyValuedays are removed.
Returns
- Task<List<PatientObservation>>
A List<T> containing the documents that were deleted.
DeleteOlderNumberAsync(string, int)
Keeps only the retentionPolicyValue most recent observations for the specified name,
deleting all older ones. Returns the documents that were deleted for downstream processing.
public Task<List<PatientObservation>> DeleteOlderNumberAsync(string name, int retentionPolicyValue)
Parameters
namestringThe observation name to apply the retention policy to.
retentionPolicyValueintThe maximum number of observations to retain. The remainder are deleted.
Returns
- Task<List<PatientObservation>>
A List<T> containing the documents that were deleted. Returns an empty list when nothing had to be deleted.
DeleteOlderSecondsAsync(string, int)
Deletes all observations with the specified name that are older than the configured number of seconds. Returns the documents that were deleted for downstream processing.
public Task<List<PatientObservation>> DeleteOlderSecondsAsync(string name, int retentionPolicyValue)
Parameters
namestringThe observation name to filter by.
retentionPolicyValueintThe retention window expressed in seconds. Observations older than
UtcNow - retentionPolicyValueseconds are removed.
Returns
- Task<List<PatientObservation>>
A List<T> containing the documents that were deleted.
ExistBySystemId(ObjectId, string)
Asynchronously checks whether an observation exists for a given patient with the specified SystemId.
Only the document identifier is projected, making the query lightweight.
public Task<bool> ExistBySystemId(ObjectId patientid, string systemId)
Parameters
patientidObjectIdThe unique identifier of the patient.
systemIdstringThe external system identifier to look up.
Returns
ExpireExpiredObservations(List<ConfigObservation>)
Asynchronously marks observations as expired when their time is older than the configured expiration
window defined by the supplied ConfigObservation entries. Only observations that are not
already marked as expired are updated. Errors are logged and swallowed.
public Task ExpireExpiredObservations(List<ConfigObservation> configObservationsToExpire)
Parameters
configObservationsToExpireList<ConfigObservation>A list of ConfigObservation entries describing the observation names and their expiration windows (in minutes). Observations whose
timeis older thanDateTime.Now - expiresminutes are marked as expired.
Returns
FindAll()
Asynchronously returns every observation stored in the collection.
public Task<IEnumerable<PatientObservation>> FindAll()
Returns
- Task<IEnumerable<PatientObservation>>
An IEnumerable<T> containing all observations.
FindAllLastPatientObservationTime()
Asynchronously retrieves, for every patient with observations, the timestamp of the most recent observation.
Implemented as a server-side aggregation that groups by patientid and selects the latest time value.
public Task<Dictionary<ObjectId, DateTime>> FindAllLastPatientObservationTime()
Returns
- Task<Dictionary<ObjectId, DateTime>>
A Dictionary<TKey, TValue> mapping each patient's MongoDB.Bson.ObjectId to the UTC timestamp of their latest observation.
FindAnyBeforeDate(ObjectId, DateTime)
Asynchronously retrieves all observations for a patient whose time is strictly before the specified date.
public Task<List<PatientObservation>> FindAnyBeforeDate(ObjectId patientId, DateTime date)
Parameters
patientIdObjectIdThe unique identifier of the patient.
dateDateTimeThe upper-bound (exclusive) observation
time.
Returns
- Task<List<PatientObservation>>
A List<T> containing the matching observations, which may be empty.
FindAnyWithSameDate(ObjectId, string?, DateTime)
Asynchronously retrieves all observations for a patient with a given name whose time exactly matches the provided value.
public Task<List<PatientObservation>?> FindAnyWithSameDate(ObjectId patientId, string? name, DateTime date)
Parameters
patientIdObjectIdThe unique identifier of the patient.
namestringThe observation name to match. Can be null.
dateDateTimeThe exact
timevalue to match.
Returns
- Task<List<PatientObservation>>
A Task<TResult> representing the asynchronous operation. The task result contains a list of matching observations, which may be empty.
FindById(ObjectId)
Asynchronously finds an observation by its unique identifier.
public Task<PatientObservation?> FindById(ObjectId id)
Parameters
idObjectIdThe MongoDB.Bson.ObjectId of the observation to retrieve.
Returns
- Task<PatientObservation>
A Task<TResult> representing the asynchronous operation. The task result contains the PatientObservation if found; otherwise, null.
FindByName(string, DateTime?)
Asynchronously finds observations whose name matches the given pattern (case-insensitive substring/regex),
optionally restricted to those with a time greater than fromDate.
public Task<IEnumerable<PatientObservation>> FindByName(string name, DateTime? fromDate = null)
Parameters
namestringThe regex pattern to match against the observation name. Cannot be null, empty, whitespace, or longer than 100 characters.
fromDateDateTime?Optional inclusive lower bound on the observation
time.
Returns
- Task<IEnumerable<PatientObservation>>
An IEnumerable<T> containing the matching observations.
Exceptions
- BadRequestException
Thrown when
nameis null, empty, or whitespace, or when its length exceeds 100 characters.
FindByPatientId(ObjectId)
Asynchronously retrieves all observations for a patient by the patient's identifier.
public Task<List<PatientObservation>?> FindByPatientId(ObjectId id)
Parameters
idObjectIdThe MongoDB.Bson.ObjectId of the patient whose observations should be retrieved.
Returns
- Task<List<PatientObservation>>
A Task<TResult> representing the asynchronous operation. The task result contains a list of observations, which may be empty.
FindByPatientIdAndCodingSystemAsync(ObjectId, string, string)
Asynchronously returns a cursor over all observations for a patient that match a given coding system and observation name.
public Task<IAsyncCursor<PatientObservation>> FindByPatientIdAndCodingSystemAsync(ObjectId patientId, string codingSystem, string name)
Parameters
patientIdObjectIdThe unique identifier of the patient.
codingSystemstringThe coding system to filter by.
namestringThe observation name to filter by.
Returns
- Task<IAsyncCursor<PatientObservation>>
An MongoDB.Driver.IAsyncCursor<TDocument> containing the matching observations, retrieved with a server-side batch size of 100.
FindByPatientIdAsync(ObjectId)
Asynchronously returns a cursor over all observations for a given patient, using a server-side batch size of 100.
public Task<IAsyncCursor<PatientObservation>> FindByPatientIdAsync(ObjectId patientId)
Parameters
patientIdObjectIdThe unique identifier of the patient.
Returns
- Task<IAsyncCursor<PatientObservation>>
An MongoDB.Driver.IAsyncCursor<TDocument> that can be enumerated to retrieve the patient's observations.
FindLastNotExpiredObservatonsByPatient(ObjectId, string, int?, int?)
Asynchronously retrieves the most recent observations for a patient with a given name, optionally bounded to a recent time window and an explicit maximum count.
public Task<IEnumerable<PatientObservation>> FindLastNotExpiredObservatonsByPatient(ObjectId patientId, string name, int? endAfter = null, int? num = null)
Parameters
patientIdObjectIdThe unique identifier of the patient.
namestringThe observation name to filter by.
endAfterint?Optional look-back window in seconds. When provided, only observations whose
timeis greater than or equal toUtcNow - endAfterare returned.numint?Optional maximum number of observations to return. null means no limit.
Returns
- Task<IEnumerable<PatientObservation>>
An IEnumerable<T> containing the matching observations ordered from newest to oldest.
FindLastObservationBeforeDate(ObjectId, string?, DateTime)
Asynchronously finds the most recent observation for a patient with the given name that occurred strictly before the specified date.
public Task<PatientObservation?> FindLastObservationBeforeDate(ObjectId patientId, string? name, DateTime date)
Parameters
patientIdObjectIdThe unique identifier of the patient.
namestringThe observation name to search for. Can be null.
dateDateTimeThe upper-bound (exclusive) observation
time.
Returns
- Task<PatientObservation>
A Task<TResult> representing the asynchronous operation. The task result contains the most recent matching observation, or null if no observation matches.
FindLastObservations(ObjectId, string, string, int)
Asynchronously finds the most recent observations of a specific type (by coding system and code) for a patient.
Results are sorted by time in descending order and limited to num entries.
public Task<IEnumerable<PatientObservation>> FindLastObservations(ObjectId patientId, string codingSystem, string code, int num = 2)
Parameters
patientIdObjectIdThe unique identifier of the patient.
codingSystemstringThe coding system used (for example, LOINC, SNOMED).
codestringThe code identifying the observation type within the coding system.
numintThe maximum number of recent observations to return. Defaults to 2.
Returns
- Task<IEnumerable<PatientObservation>>
An IEnumerable<T> containing the matching observations ordered from newest to oldest.
FindLastObservationsByCodingSystem(ObjectId, string, int)
Asynchronously finds the most recent observations of a specific coding system for a patient.
Results are sorted by time in descending order and limited to num entries.
public Task<List<PatientObservation>> FindLastObservationsByCodingSystem(ObjectId patientId, string codingSystem, int num = 10)
Parameters
patientIdObjectIdThe unique identifier of the patient.
codingSystemstringThe coding system to filter observations by.
numintThe maximum number of recent observations to return. Defaults to 10.
Returns
- Task<List<PatientObservation>>
A List<T> containing the matching observations ordered from newest to oldest.
FindLatestUniqueValuesByName(ObjectId, string, int?)
Asynchronously retrieves, for a given patient and observation name, the latest occurrence of each distinct value.
Optionally restricts the result to observations not older than expires seconds.
public Task<List<PatientObservation>> FindLatestUniqueValuesByName(ObjectId patientId, string name, int? expires)
Parameters
patientIdObjectIdThe unique identifier of the patient.
namestringThe observation name to search for.
expiresint?Optional expiration window expressed in seconds. When provided, only observations newer than
UtcNow - expiresseconds are considered.
Returns
- Task<List<PatientObservation>>
A List<T> containing the most recent observation for each distinct value.
FindNotExpired(List<string?>?)
Asynchronously retrieves observations that are not marked as expired, optionally restricted to a list of observation names. Observations with a null name are excluded from the result.
public Task<IEnumerable<PatientObservation>> FindNotExpired(List<string?>? filterObservations)
Parameters
filterObservationsList<string>Optional list of observation names to match. When null, all non-null named observations are considered (still subject to the not-expired filter).
Returns
- Task<IEnumerable<PatientObservation>>
An IEnumerable<T> containing the matching non-expired observations.
GetCollectionName()
Gets the name of the MongoDB collection used to store patient observations. Falls back to the default "patients_observations" collection name when not configured in the API settings.
public override string GetCollectionName()
Returns
- string
The collection name retrieved from the API settings, or "patients_observations" if not configured.
GetPaginatedObservations(PaginationFilter)
Builds a paginated, sorted, and filtered query over observations.
Results are sorted by time in descending order. When a FilteredRequest
is provided, observations can be filtered by name list and patient identifier. A mandatory time window
(defaulting to DateTime.MinValue / DateTime.MaxValue) is always applied.
public IFindFluent<PatientObservation, PatientObservation> GetPaginatedObservations(PaginationFilter filter)
Parameters
filterPaginationFilterThe PaginationFilter containing pagination and filter criteria.
Returns
- IFindFluent<PatientObservation, PatientObservation>
An MongoDB.Driver.IFindFluent<TDocument, TProjection> instance that can be used to further refine and execute the query.
InsertOneAsync(PatientObservation)
Asynchronously inserts a single patient observation, automatically retrying with a new MongoDB.Bson.ObjectId when a MongoDB duplicate-key error is encountered. The retry strategy is bounded by an internal maximum.
public Task InsertOneAsync(PatientObservation patientObservation)
Parameters
patientObservationPatientObservationThe PatientObservation to insert. If a duplicate-key error occurs, a new identifier is generated and the insert is retried.
Returns
Exceptions
- MongoWriteException
Rethrown after the maximum number of retries has been reached when a duplicate-key error keeps occurring.
- Exception
Rethrown when an unexpected error occurs during the insert operation.
Update(PatientObservation)
Asynchronously updates a single observation by replacing its document with the provided instance.
public Task Update(PatientObservation observation)
Parameters
observationPatientObservationThe PatientObservation whose MongoDB.Bson.ObjectId identifies the document to update.
Returns
UpdateExpiredObservations(List<PatientObservation>)
Asynchronously marks the supplied list of observations as expired by setting their Expired flag to true.
public Task UpdateExpiredObservations(List<PatientObservation> expiredObservations)
Parameters
expiredObservationsList<PatientObservation>The list of PatientObservation instances to mark as expired. The set of identifiers is used to build the update filter.
Returns
UpdateMany(IEnumerable<PatientObservation>, UpdateDefinition<PatientObservation>)
Asynchronously applies the given update definition to a set of observations identified by their identifiers.
public Task UpdateMany(IEnumerable<PatientObservation> patientObservations, UpdateDefinition<PatientObservation> update)
Parameters
patientObservationsIEnumerable<PatientObservation>The observations whose identifiers form the target set of the update.
updateUpdateDefinition<PatientObservation>The MongoDB.Driver.UpdateDefinition<TDocument> describing the changes to apply to each matching document.
Returns
UpdateManyObjectId(string, ObjectId, ObjectId)
Asynchronously updates all documents in the collection where the specified field equals oldId,
setting that field to the new id. Thin wrapper around the protected helper on the base repository.
public Task UpdateManyObjectId(string nameId, ObjectId id, ObjectId oldId)
Parameters
nameIdstringThe name of the field to match and update.
idObjectIdThe new MongoDB.Bson.ObjectId value to assign.
oldIdObjectIdThe existing MongoDB.Bson.ObjectId value to replace.