Search code examples
mongodbf#mongodb-.net-driver

MongoDb and F#: How to select distinct values?


I'm using the latest (at the time of writing) version (2.8) of the C# MongoDb driver. I am using it from F#. I want to select the distinct values of a field in a collection.

From this old question, the following does not work:

let client = new MongoClient(connString)
let db = client.GetDatabase("AirQuality")
let col = db.GetCollection<ReadingValue>("ReadingValue")
let res = col.DistinctAsync<string>("SensorName","{}")

The type string is not compatible with the type FieldDefinition<ReadingValue,string>.

From this answer, the following does not work either

let fd : FieldDefinition<ReadingValue, string> = "" :> FieldDefinition<ReadingValue, string>

Solution

  • In C# you can implicitly convert from string to FieldDefinition<T> (class implements implicit operator). Since types conversion works in a different way in F# you can use StringFieldDefinitionClass

    let field = new StringFieldDefinition<ReadingValue, string>("SensorName")
    let result = col.Distinct<string>(field, Builders<ReadingValue>.Filter.Empty)