findOne method

Future<MongoDocument?> findOne({
  1. dynamic filter,
  2. Map<String, ProjectionValue>? projection,
})

Finds a document in the collection according to the given filter

Implementation

Future<MongoDocument?> findOne(
    {filter, Map<String, ProjectionValue>? projection}) async {
  var filterCopy = <String, dynamic>{};
  if (filter != null) {
    assert(filter is Map<String, dynamic> || filter is LogicalQueryOperator);

    if (filter is Map<String, dynamic>) {
      // convert 'QuerySelector' into map, too
      filter.forEach((key, value) {
        if (value is QueryOperator) {
          filterCopy[key] = value.values;
        } else
          filterCopy[key] = value;
      });
    }
    if (filter is LogicalQueryOperator) {
      filterCopy = filter.values;
    }
  }

  var projectionMap = projection?.map((k, v) => MapEntry(k, v.value));

  String? resultJson = await (FlutterMongoRealm.findFirstDocument(
    collectionName: this.collectionName,
    databaseName: this.databaseName,
    filter: BsonDocument(filterCopy).toJson(),
    projection: projectionMap == null ? null : jsonEncode(projectionMap),
  ));

  // return null document for empty query
  if (resultJson == null) {
    return null;
  }

  return MongoDocument.parse(resultJson);
}