Table of Contents

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

apiSettings IOptions<ApiSettings>

The application API settings containing configuration values, including the collection name. Must not be null.

database IMongoDatabase

The MongoDB database instance used to access the collection.

logger ILogger<ObservationRepository>

The logger used to record diagnostic and error information.

Exceptions

ArgumentNullException

Thrown when apiSettings is 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

patientId ObjectId

The 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

patientId ObjectId

The unique identifier of the patient.

groupedField GroupedField

A 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

patientId ObjectId

The unique identifier of the patient.

num int

The maximum number of observations to return per observation name.

filterObservations List<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

patientId ObjectId

The unique identifier of the patient.

filterObservations List<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

patientId ObjectId

The unique identifier of the patient.

num int

The maximum number of observations to return per observation name.

lastDate DateTime

The inclusive upper bound (UTC) for the observation time field.

filterObservations List<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

Task

A Task representing the asynchronous index creation operation.

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

id ObjectId

The MongoDB.Bson.ObjectId of the observation to delete.

Returns

Task

A Task representing the asynchronous delete operation.

DeleteByPatientId(ObjectId)

Asynchronously deletes all observations associated with the specified patient.

public Task DeleteByPatientId(ObjectId id)

Parameters

id ObjectId

The MongoDB.Bson.ObjectId of the patient whose observations should be removed.

Returns

Task

A Task representing the asynchronous delete operation.

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

name string

The observation name to filter by.

retentionPolicyValue int

The retention window expressed in days. Observations older than UtcNow - retentionPolicyValue days 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

name string

The observation name to apply the retention policy to.

retentionPolicyValue int

The 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

name string

The observation name to filter by.

retentionPolicyValue int

The retention window expressed in seconds. Observations older than UtcNow - retentionPolicyValue seconds 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

patientid ObjectId

The unique identifier of the patient.

systemId string

The external system identifier to look up.

Returns

Task<bool>

true if a matching observation exists; otherwise, false.

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

configObservationsToExpire List<ConfigObservation>

A list of ConfigObservation entries describing the observation names and their expiration windows (in minutes). Observations whose time is older than DateTime.Now - expires minutes are marked as expired.

Returns

Task

A Task representing the asynchronous update operation.

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

patientId ObjectId

The unique identifier of the patient.

date DateTime

The 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

patientId ObjectId

The unique identifier of the patient.

name string

The observation name to match. Can be null.

date DateTime

The exact time value 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

id ObjectId

The 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

name string

The regex pattern to match against the observation name. Cannot be null, empty, whitespace, or longer than 100 characters.

fromDate DateTime?

Optional inclusive lower bound on the observation time.

Returns

Task<IEnumerable<PatientObservation>>

An IEnumerable<T> containing the matching observations.

Exceptions

BadRequestException

Thrown when name is 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

id ObjectId

The 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

patientId ObjectId

The unique identifier of the patient.

codingSystem string

The coding system to filter by.

name string

The 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

patientId ObjectId

The 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

patientId ObjectId

The unique identifier of the patient.

name string

The observation name to filter by.

endAfter int?

Optional look-back window in seconds. When provided, only observations whose time is greater than or equal to UtcNow - endAfter are returned.

num int?

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

patientId ObjectId

The unique identifier of the patient.

name string

The observation name to search for. Can be null.

date DateTime

The 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

patientId ObjectId

The unique identifier of the patient.

codingSystem string

The coding system used (for example, LOINC, SNOMED).

code string

The code identifying the observation type within the coding system.

num int

The 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

patientId ObjectId

The unique identifier of the patient.

codingSystem string

The coding system to filter observations by.

num int

The 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

patientId ObjectId

The unique identifier of the patient.

name string

The observation name to search for.

expires int?

Optional expiration window expressed in seconds. When provided, only observations newer than UtcNow - expires seconds 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

filterObservations List<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

filter PaginationFilter

The 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

patientObservation PatientObservation

The PatientObservation to insert. If a duplicate-key error occurs, a new identifier is generated and the insert is retried.

Returns

Task

A Task representing the asynchronous insert operation.

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

observation PatientObservation

The PatientObservation whose MongoDB.Bson.ObjectId identifies the document to update.

Returns

Task

A Task representing the asynchronous update operation.

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

expiredObservations List<PatientObservation>

The list of PatientObservation instances to mark as expired. The set of identifiers is used to build the update filter.

Returns

Task

A Task representing the asynchronous update operation.

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

patientObservations IEnumerable<PatientObservation>

The observations whose identifiers form the target set of the update.

update UpdateDefinition<PatientObservation>

The MongoDB.Driver.UpdateDefinition<TDocument> describing the changes to apply to each matching document.

Returns

Task

A Task representing the asynchronous update operation.

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

nameId string

The name of the field to match and update.

id ObjectId

The new MongoDB.Bson.ObjectId value to assign.

oldId ObjectId

The existing MongoDB.Bson.ObjectId value to replace.

Returns

Task

A Task representing the asynchronous update operation.