C# Mongodb Deserialize List of BsonDocument types to List of Class Types

I am trying to deserialize a List of BsonDocuments to class Type using BsonSerializer but I am getting an error “cannot convert from ‘System.Collections.Generic.List<MongoDB.Bson.BsonDocument>’ to ‘MongoDB.Bson.BsonDocument’”. It only works for a single BsonDocument Type.

How do I Deserialize a BsonDocument list to list class type?

var projection = Builders<Property>.Projection
            .Include(x => x.Type);

        var values= await MongoCollection
                                .Find(Builders<Property>.Filter.Empty)
                                .Project(projection)
                                .ToListAsync()
                                .ConfigureAwait(false);

        var test = BsonSerializer.Deserialize<IEnumerable<Property>>(values);

encounter the same problem

Try using LINQ to deserialize each BsonDocument individually:

var test = values.Select(v => BsonSerializer.Deserialize<Property>(v)).ToList();
1 Like