I am trying to return a list of distinct file types from a MongoDB collection using VB.Net (similar to C#.Net). Since each document has an unique id
regardless of similar file types, the code returns duplicates. What am I missing here? I tried GroupBy
but it didn't work.
Public Function GetAllFileTypes() As List(Of UXFiles)
Dim m_List As New List(Of UXFiles)
Dim db As IMongoDatabase = DatabaseService.GetDBcontext()
Dim files = db.GetCollection(Of BsonDocument)("Files").Find(New BsonDocument).ToList
m_List = files.Select(Function(_file) ConvertFile(_file)).Distinct().ToList()
Return m_List
End Function
Private Function ConvertFile(fileDocument As BsonDocument) As UXFiles
Dim file As New UXFiles With {
.ID = If(fileDocument.Contains("id"), fileDocument.GetElement("id").Value.ToString, ""),
.Name = If(fileDocument.Contains("name"), fileDocument.GetElement("name").Value.ToString, ""),
.Type = If(fileDocument.Contains("type"), fileDocument.GetElement("type").Value.ToString, "")
}
Return file
End Function
Distinct eliminates duplicate results from the result set. If you include _id of each document in the results, there are no duplicates since each _id is unique. You need to either project some fields (e.g. file type if you want to know what file types exist) or use something like $group with $first.