I have a line of code that gets data from MongoDB
IAsyncCursor<BsonDocument> result = await _repository.GetBsonAggregateAsync(pipeline);
var resultdata = await result.ToListAsync();
The result I get in resultdata is given below
"{ ""_id"" : { ""type"" : ""Printer"" }, ""total"" : 1 }"
I am unsure how to change it into a printermodel class given below
class PrinterModel
{
public string Type { get; set; }
public int Total { get; set; }
}
Please help, I am very new to this.
I doubt the result you get from the resultData
is a single object/BsonDocument
. Its type is List<BsonDocument>
which is an array of BsonDocument
(s).
Apart from my concern about your returned data, you can use Linq to convert from the BsonDocument
to PrinterModel
.
using System.Linq;
List<PrinterModel> printers = resultData
.Select(x => new PrinterModel
{
Type = x["_id"]["type"].ToString(),
Total = x["total"].ToInt32()
})
.ToList();
Suppose you are looking for a solution that directly converts into your model class without manually mapping the properties using the approach above. In that case, you need to modify your query pipeline to match your model class structure.
Your query pipeline should consist:
{
$project: {
_id: 0,
type: "$_id.type",
total: "$total"
}
}
the $project
stage as the last stage.
Register the camel case convention before querying data.
using MongoDB.Bson.Serialization.Conventions;
var pack = new ConventionPack();
pack.Add(new CamelCaseElementNameConvention());
ConventionRegistry.Register("camel case", pack, t => true);
IAsyncCursor<BsonDocument> result = await _repository.GetBsonAggregateAsync(pipeline);
var resultdata = await result.ToListAsync();
List<PrinterModel> printers = BsonSerializer.Deserialize<List<PrinterModel>>(resultData.ToJson());
// Or
// List<PrinterModel> printers = resultData
// .Select(x => BsonSerializer.Deserialize<PrinterModel>(x))
// .ToList();